0

I tried to make a clone of an arraylist so there will be two lists created. After that, I tried to modify the property of an element in one of the lists. When I compared the lists, it should have given me false for equal result but instead it is true. I assume this got to do with the pointer of the element or list. Is there any solution to fix that?

My code is like this:

    List<UnifiedBucket> ubsCopy = new ArrayList<>(ubs);
    ubsCopy.get(14).setRawPolicy(null);
    UnifiedBucket ub1 = ubs.get(14);
    UnifiedBucket ub2= ubsCopy.get(14);
    System.out.println(ub1 == ub2);
    System.out.println(ub1.getRawPolicy().equals(ub2.getRawPolicy()));
Ihsan Haikal
  • 1,085
  • 4
  • 16
  • 42

1 Answers1

1

what you want to have is a deep copy but the constructor does shallow copy , look at public ArrayList(Collection c)

if you want to make a deep copy use Iterator on ArrayList like this :

    List<UnifiedBucket> UnifiedBucketClone = new ArrayList<>();

    Iterator<UnifiedBucket> iterator = ubs.iterator();
    while(iterator.hasNext()){
        UnifiedBucketClone .add((UnifiedBucket) iterator.next().clone());
    }