Create a Java object from a list of other objects [closed]

0

I have a class Torres that is composed of other classes Plaques and Memories all inherit from Producto :

public class Torres extends Producto {
    private Plaques plaques;
    private Memories memories;

    public Torres(String codiIntern, String descripcio, String nomFab, double preuC, double preuBrut, int estoc,Plaques plaques,Memories memories) {
        super(codiIntern, descripcio, nomFab, preuC, preuBrut, estoc);
        this.memories = memories;
        this.plaques = plaques;
    }
}

I also have a TreeMap that represents the components with which the object Torres will be formed, formed with different Plaques and Memories . The key is the codiIntern, and the value is only objects Plaques and Memories

torres = new TreeMap<String,Producto>();

My question would be how to make a method that creates an object of Torres with all the elements of the list TreeMap . If for example there is 2 Plaques and 1 Memories should create a Tower that has those 2 Plaques and 1 Memories .

    
asked by FranEET 11.01.2017 в 22:55
source

1 answer

1

The truth is that the question is not very clear and also missing information about the classes Plaques and Memories , but if I understood correctly, what you want is to build objects Torres with the information you have in the map of objects Plaques and Memories and your doubt is how to know which is of each type to move it to one property or another. To know the type you should use instanceof .

If all the objects in the collection belong to the same object Torres you could change the objects by collections and add them using properties instead of adding the objects directly in the constructor. The class would look like this:

public class Torres extends Producto {
    private List<Plaques> plaques = new ArrayList<Plaques>();
    private List<Memories> memories = new ArrayList<Memories>();

    public List<Plaques> getPlaques() {
        return plaques;
    }

    public void setPlaques(List<Plaques> plaques) {
        this.plaques = plaques;
    }

    public List<Memories> getMemories() {
        return memories;
    }

    public void setMemories(List<Memories> memories) {
        this.memories = memories;
    }

    public Torres(String codiIntern, String descripcio, String nomFab, double preuC, double preuBrut, int estoc) {
        super(codiIntern, descripcio, nomFab, preuC, preuBrut, estoc);
    }
}

And you could go through it like this:

Torres newTorre = new Torres(null, null, null, 0, 0, 0);
Map<String, Producto> torres = new TreeMap<String, Producto>();

for(Producto myTorres: torres.values()) {
    if(myTorres instanceof Plaques) {
        newTorre.getPlaques().add((Plaques) myTorres);
    } else {
        newTorre.getMemories().add((Memories) myTorres);
    }
}

This, assuming that objects Plaques and Memories extend from Producto .

    
answered by 12.01.2017 / 07:51
source