I've recently run into a question that makes me wonder if I'm misunderstanding a fundamental concept in Java programming. In this program I wrote, I make a copy of an array list, and then remove some items from that copy, but it seems like it's removing those items from the original array list as well, is that right? If I make object 2 equal to object 1, then anything I do to object 2 also happens to object 1?
Here's the code:
When I run this code, after I remove an allele from refAllelesLocal, it is removed from the ArrayList referenceAlleles also, is that supposed to happen?
You aren't making a copy of the list. The line:
copies the reference, which means you end up with two variables pointing at the same ArrayList. If you want a copy, try this:
(which uses what's known as a "copy-constructor").
The following line is just taking the reference to the memory location for referenceAlleles and storing it in refAllelesLocal.
The list interface exposes a "Clone" method which as documented is going to give you a 'shallow' copy of the list. I have not used it myself, but my recollection is this is advising that the Objects in the list will be the same references as the original list and hence changes to the objects themselves would be shared among the two lists.
it never makes a copy of an object. It only copies the refrence that's in o1 into o2, so that both reference variables point to the same object.
So, when you do this:
you're not copying your List. You're merely copying the reference value from referenceAlleles into refAllelesLocal, so that both variables point to the same ArrayList object.
You can do this however:
That doesn't work with all classes--it's not a built-in language feature. But all the Collections Framework implementation classes do have copy constructor like that.
If you do this, you have two distinct, independent List objects. Adding to or removing from one, changing the order of one, etc., does not affect the other.
However, the element objects were not copied. That is, position 0 in the second List just holds a reference to the same object as position 0 in the first List. Both Lists point to the same String object for position 0, both point to the same for position 1, etc. So if you change the contents of that object, the change will be seen by both Lists. In this case, it's not an issue, since String is immutable. If it were, say List<Date>, however, and you did list1.get(0).setTime(123);, then, since there's a single Date object referred to by both lists, both lists see that change.