-1

Before entering question, I know other than primitive type, everything is stored by its reference number. My java code structure is something like this..... First I have driver, reservation and car classes. The relationship between them is driver is a driver who performed reservation and car is booked up to be driven that is stored in reservation class.

Driver will take care of reservation. Cars have a few primitive types information. Multiple cars can be stored into the reservation (primitive and ArrayList). But one driver (ArrayList) (from driver class) can have multiple reservations. So, when I allow users to view what driver has in his reservations, I would like to deep copy everything in the ArrayList since everything except for primitive types are reference numbers.

Anyway, I will make a copy of array list for reservation in driver class.

In my driver class, and this is a accessor and when it is passing the ArrayList, I attempted to deep copy first and pass the ArrayList.

public ArrayList<Reference> getReference() {    

    copiedRef = new ArrayList<Reference>();

    //references have been declared above
    for (int i = 0; i < references.size(); i++) {
        copiedRef.add(references.get(i));
        //getting each element in the arrayList one by one and push to a new ArrayList
    }

    return copiedRef;
}

Is this doing deep copy? And if I need to use clone().

How would I improve? (clone does shallow copy, I don't think clone can help for deep copy or I could misunderstand other posts).

msrd0
  • 7,816
  • 9
  • 47
  • 82
user3599762
  • 1
  • 1
  • 1

2 Answers2

3

Your code achieves no copying at all, except for the list of references. It is equivalent to the one-liner

copiedRef = new ArrayList<>(references);

clone can do deep copying, and it is designed specifically to support that. Only the default implementation in Object does shallow copying.

However, it is usually not recommended to bother with clone due to its arcane contract requirements and limitations with respect to final fields. You can instead provide a copy constructor of your domain class.

Usually the simplest way, involving the least code, to achieve deep copying is through in-memory serialize-deserialize cycle. Only note that in this case, "performance" is a dirty word :)

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

No it is not.

copiedRef.add(references.get(i));

Above code gets each object of type Reference, and stores that references into this new arraylist(copied Ref). You basically need to create a new instance with the same state as each references.get(i) object.

If your Reference type has all the primitive type, you can call (Reference)references.get(i).clone() while adding these references.

ajay.patel
  • 1,957
  • 12
  • 15