2

I have copied an ArrayList as I want to keep original values of my source Arraylist.

If I change first item of my source ArrayList, it automatically changes first item value of new ArrayList.

I used a few code blocks but I couldn't solve this problem.

ArrayList<SicilBakiye> resultCopy = new ArrayList<SicilBakiye>();
resultCopy.addAll(result);  // 1.method

resultCopy=result.clone();  // 2.method

resultCopy=result;  // 3.method

If I change :

result.get(0).setid(5);

This automatically changes :

resultCopy.get(0).getid() // return 5

How can I solve ? Thanks for your ideas

5

5 Answers 5

4

Let's have a look at the 3 methods you provided and then address your problem:

ArrayList resultCopy = new ArrayList();
resultCopy.addAll(result); // 1.method

This creates an empty array list and adds all elements from result to the copy. Any change to result itself (e.g. adding a new element or removing one) is not reflected in the copy.

resultCopy=result.clone(); // 2.method

That basically does the same as above, at least of the standard implementation is used - just that the copy is created inside of clone() and then returned.

resultCopy=result; // 3.method

This just assigns the instance that result references to resultCopy, i.e. you have 2 references to the same list. Thus any change made to result is reflected by resultCopy and vice versa.

Now to your actual problem:

result.get(0).setid(5); does not change result but the element inside result. Thus you also see that change in resultCopy.

It's the same as if I put you into two courses at school. If you leave one you'll still be in the other and vice versa. But if your age changes (which it will ;) ) the teacher in each course will get the same answer.

What you're probably after is called a deep copy: you copy the list as well as the elements inside the list. If those reference other objects you might have to copy them as well - where to stop depends on your requirements and the structure of your objects.

To create deep copies of your objects you could either implement and call clone() where needed, use a library that clones via reflection (e.g. Apache Commons BeanUtils) or use a mapping library (e.g. Dozer, Mapstruct, etc.).

Sign up to request clarification or add additional context in comments.

7 Comments

for 3.method: already change resultCopy. Not result. for 1.method: reflected copy. You can try.
@mobileprogramming I'm not sure what you mean by that. resultCopy=result; will make both variables reference the exact same list.
OK. How can I keep values of Copy ArrayList? Which method may I use ?
@mobileprogramming read my last two paragraphs. Those should contain what you want (at least what I guess you want).
for(SicilBakiye bakiye : result) { resultCopy.add(bakiye.clone()); } I wrote this block but clone method is wrong. Warning message : "clone() has protected access in Java.lang.object"
|
0

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

see this

Comments

0

You need to do a "deep copy" of the ArrayList. That is you need to copy (clone) each of the objects in the list.

When you do a shallow copy of the ArrayList your second ArrayList is pointing to the same objects as the original.

ArrayList<SicilBakiye> resultCopy = new ArrayList<SicilBakiye>();
for (SicilBakiye obj : original) {
    resultCopy.add((SicilBakiye)obj.clone());
}

Comments

0

okey I solved. I use this code:

  for(SicilBakiye bakiye : result) {
            resultCopy.add((SicilBakiye) bakiye.clone());
        }

and

SicilBakiye implements Cloneable{ 
    .....
public SicilBakiye clone() {
        try {
            return (SicilBakiye) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

1 Comment

That's more of a side note but from my experience it's best to either throw an exception (in your case you could do throw new RuntimeException(e)) or handle it (e.g. by logging it). Doing both can lead to confusion.
0

Below example will helps to others if changing any value in clone ArrayList

ArrayList<String> arrayListObject = new ArrayList<>();

arrayListObject.add("A");
arrayListObject.add("B");
arrayListObject.add("C");
arrayListObject.add("D");

System.out.println("Original Arraylist Values::" + arrayListObject);

ArrayList<String> arrayListClone = (ArrayList<String>) arrayListObject.clone();
System.out.println("Clone Arraylist Values::" + arrayListClone);

System.out.println("After changed position at 0 index in Clone Arraylist");
arrayListClone.set(0, "AA");

System.out.println("Original Arraylist Values::" + arrayListObject);
System.out.println("Clone Arraylist Changed Values::" + arrayListClone);

Output

Original Arraylist Values::[A, B, C, D]
Clone Arraylist Values::[A, B, C, D]

After changed position at 0 index in Clone Arraylist
Original Arraylist Values::[A, B, C, D]
Clone Arraylist Changed Values::[AA, B, C, D]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.