Doubt treeMap in Java

3

I would like to know if when I make a list treemap of objects Producto which has byproducts in inheritance type:

ProductoA
ProductoB

Could you just show the ProductoA ?

This is how I believe it:

public Cataleg(){
    super();
    this.map_catalogo= new TreeMap<String,Producto>();
}

After doing a method where I add the products either A or B , I can show them all like this:

public void mostrarProductos(){
    System.out.println("Productos disponibles en almacen: ");
    for(Producto p : map_catalogo.values()) {
        System.out.println(p);
    }
}

I would like to know how you can only show me the ProductosA (which is a subclass of Producto ).

    
asked by FranEET 11.01.2017 в 16:44
source

1 answer

2

In java is the operator instanceof that determines whether an object it is an instance of a specific class.

In your case you should use it like this:

public void mostrarProductos(){
    System.out.println("Productos disponibles en almacen: ");
    for(Producto p : map_catalogo.values()) {
      if( p instanceof ProductoA) {
        System.out.println(p.toString());
      }
    }
}    

If the product class p is ProductoA returns true and if not false

Note: I do not know if you obviated it because it is not relevant to your question, but the p object should have a toString() method that shows the Product information. A very good answer explains what happens if you do not create your own toString() and use the default Object

    
answered by 11.01.2017 / 17:03
source