0

I am new to java and I would really appreciate some suggestions.

I have these 2 classes:

public class Value {
    public Integer importance;
    public Float price;
    public String name;
}

public class Attribute {
    public String type;
    public String name;
    public Value value;
}

Now I have this ArrayList of Attribute objects:

ArrayList<Attribute> attributes

What I want is to deep copy elements (not only references) in attributes into this other ArrayList:

ArrayList<Attribute> newAttributes

I saw that this isn't working:

for(Attribute attribute : atributes) {
        newAtributes.add(attribute);
}

What should I do?

aki
  • 1
  • 2

1 Answers1

0

First you have create copy of the object using Cloneable or Copy Constructor:

public class Value {
    public Integer importance;
    public Float price;
    public String name;

    public Value(Value value) {
        importance = value.importance;
        price = value.price;
        name = value.name;
    } 
}

public class Attribute {
    public String type;
    public String name;
    public Value value;

    public Attribute(Attribute attribute) {
        type = attribute.type;
        name = attribute.name;
        value = new Value(attribute.value);
    }
}

Now you're ready to create deep array copy:

List<Attribute> attributes = new ArrayList<>();
List<Attribute> newAttributes = attributes.stream().map(attribute -> new Attribute(attribute)).collect(Collector.toList());
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35