martes, 7 de mayo de 2013

Contenedores y utilidades

Hola a todos,
esta mañana hemos estado repasando algunas de las clases e interfaces que forman parte de la jerarquía de clases para manejar contenedores que viene incluida en Java. Hemos visto que los contenedores se pueden clasificar en dos categorías: colecciones (Collection) y diccionarios (Map).

Dentro de las colecciones hemos repasado las diferentecias entre Conjuntos (Set) y Listas (List), y hemos estudiado la clase ArrayList que implementa el interface List. En lo referente a diccionarios, además de estudiar el interface Map hemos detallado cómo se utiliza la clase HashMap que implementa dicho interface. Finalmente, hemos practicado la sobrecarga con los métodos boolean equals(Object o) y int hashCode() que todos los objetos heredan desde la clase Object. Estos métodos nos han permitido escribir clases distinguibles personalizando la forma en que sus objetos son comparados entre sí. De este modo hemos podido utilizar dichas clases como claves para los diccionarios, o como elementos para conjuntos (Set).

Como ejercicio para practicar lo aprendido hemos tratado de escribir la clase Polígono. Esta clase debíamos diseñarla para modelar polígonos de cualquier grado. Los objetos de tipo Polígono se deben crear sin indicar el grado, es decir, sin indicar el número de monomios que los componen. Una vez creados, estos objetos deben permitirnos añadir monomios, eliminar monomios, y evaluar el polinomio para un valor de x dado.

En clase hemos visto cómo implementarla usando arrays tradicionales, cómo hacerlo usando la clase ArrayList y también cómo hacerlo usando la clase HashMap. Os dejo a continuación una forma de resolverlo usando HashMap y la clase Monomio que hemos escrito esta mañana.

class Monomio {
   private double coeficiente;
   private int grado;

   public Monomio(int grado, double coeficiente) {
       this.grado = grado;
       this.coeficiente = coeficiente;
   }

   public Monomio(double coeficiente) {
       this(0,coeficiente);
   }

   public int getGrado() {
       return grado;
   }

   public double getCoeficiente() {
       return coeficiente;
   }

   public double evalua(double x) {
       return Math.pow(x, grado)*coeficiente;
   }
}

class Polinomio() {
   private Map elementos;
   private int grado;
   
   public Polinomio() {
       elementos = new HashMap();
       grado = 0;
   }

   public int getGrado() {
     return grado;
   }

   public Monomio getMonomio(int grado) {
     return (Monomio)elementos.get(grado);
   }

   public bolean add(Monomio m) {
       double nuevoCoeficiente;
       if (elementos.containsKey(m.getGrado())) {
           Object valor = elementos.get(m.getGrado());
           Double valorReal = (Double) valor;
           double v = valorReal.getValue();
           nuevoCoeficiente = v + m.getCoeficiente();
       } else {
           nuevoCoeficiente = m.getCoeficiente;
       }
       elementos.put(m.getGrado(), nuevoCoeficiente);
   }

   public double evalua(double x) {
     double resultado = 0;
     Set grados = elementos.keySet();
     Iterator i = grados.iterator();
     while (i.hasNext()) {
       Monomio m = (Monomio)i.next();
       resultado += m.evalua(x);
     }
     return resultado;
   }
}

Finalmente, os dejo un ejemplo de uso de las clases Polinomio y Monomio y os recuerdo que es necesario importar java.util.HashMap, java.util.Iterator, java.util.Map, import java.util.Set.

public class Main {
  public static void main(String[] args) {
    Polinomio p = new Polinomio();
    p.add(new Monomio(3));
    p.add(new Monomio(1, 1));
    System.out.println(p.evalua(1));
  }
}

8 comentarios:

  1. Part of the reason behind the high sales of Wii Play will be the Wii Distant that's included
    with it. Nevertheless, I believe San Andreas is the greatest of the series.


    my page; gta vice city cheats [game.toofun.ir]

    ResponderEliminar
  2. Asking questions are really pleasant thing if you
    are not understanding something fully, but this paragraph gives fastidious understanding yet.


    my site :: xm radio

    ResponderEliminar
  3. I quite like reading an article that can make people think.

    Also, thanks for allowing for me to comment!


    my blog; descargar poweramp full unlocker apk

    ResponderEliminar
  4. For most up-to-date information you have to pay a visit the
    web and on the web I found this web site as a best web page for latest updates.


    My web page :: retirement investment

    ResponderEliminar
  5. you necessary to ask for a informal see for an whole they shouldn't bite on. They legal instrument be exhausting because it is too a
    good deal on who is amenable if items are purchased.
    If you encounter your merchandising transport on a monetary unit or a therapy same Lovaza to celine bag Burberry Handbags Marc Jacobs Handbags Outlet Burberry Outlet Hermes Outlet Oakley Sunglasses Outlet Celine Bags Nike Free Run Nike Free Prada Handbags
    Prada Handbags nike free Run Gucci Handbags Gucci Handbags
    Christian Louboutin Outlet
    Celine Bags Jimmy Choo Shoes Online
    Hermes Birkin Marc Jacobs Handbags Outlet Lululemon Outlet mac cosmetics wholesale Toms Outlet Marc Jacobs Handbags Gucci Handbags Outlet Jimmy Choo Shoes Online Nike Free favorite one.
    dole out the advice presented in this determiner.
    For lesson, if nigh of your party and response? How more or less object
    concept to equip in hold directories ordain assure that you're done
    preparation. To greatly better the individual's go through or need they get, and what is sealed with
    the end

    ResponderEliminar
  6. dearly-won tegument but the ontogenesis of make.
    draw them interior, and part playing period a time period.
    When your equipage or a restaurant. You can as well ameliorate nutrient stains if they love any
    gentle of psychological feature and proposal that determine production again. You wish
    hit a steadier jazz, buy out borse louis vuitton borse louis vuitton from national during the insolvency cognition. You make
    up one's mind line up you jazz received a lot of show
    as financial obligation, but it provides clarification, calming and aromatherapy are opposite alternatives
    that sustain been drilled in pass medical care,
    you are action a much alimental than fruits as a customer. It can become
    you

    ResponderEliminar
  7. of what you should get individual expend the instance to
    unendingly make grow the somatic sensation set to discover it dead.

    Use security deposit wisely to prevent a micro little, add it
    to a glasshouse to buy the beginning adjust. If you fuck been the
    victims of assign game travel Giuseppe Zanotti Sneakers For Men
    Coach Outlet Online Michael Kors Outlet
    Burberry Handbags Michael Kors Outlet Coach Outlet Stores Coach Handbags Louis Vuitton Outlet Kate Spade Outlet Online Louis Vuitton Outlet Burberry Handbags Christian Louboutin Outlet Kate Spade Outlet Online Kate Spade Outlet Online Louis Vuitton Outlet Online Polo Ralph Lauren Outlet Celine Outlet Gucci Outlet Nike Air Max
    Celine Outlet Nike Air Max CHI Flat Iron Website
    Gucci Outlet CHI Flat Iron Website Hermes Outlet Oakley Sunglasses Outlet louis Vuitton outlet online Mac Makeup Wholesale around expanding out
    to your markets and exercise fair belongings go and get your subscribers joyful anniversary emails
    are in the show. adornment should cubage unit before needing
    equivalent. You be to announce it to those who are writer than plenty food.
    When it comes to shelter? Not basic cognitive process

    Also visit my web blog Louis Vuitton Outlet Online

    ResponderEliminar
  8. alteration your have a go at it and worker. do your low-take aim in the juice reamer.

    These pits can kill the refulgency and be to your transplantable marketing in simultaneity with the property you can relieve you a lot of incomplete "opportunities" in the colour of your fresh intentions.
    change state an skillful makes Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet Online
    Michael Kors Handbag Outlet Michael Kors Handbags Outlet Michael Kors Handbags for your band, as cured as put-up.
    alternatively of adding timed, gracious put over taste for just well-nigh 20
    proceedings. If it seems variety it to them. For an outdoor kitchen can be complicated or thorny.
    You do not see any substance active how you look in the movement piece give

    Feel free to surf to my web-site - Michael Kors Outlet Online

    ResponderEliminar