Domanda

I have 2 ArayLists: ArrayList 1 and ArrayList 2; Basically, i need to have something like ArrayList 2 = new ArrayList(1); but if i change the second list in any way, the first list should remain the same, but if i change an item from the second list, it should also modify in the first. I've tried using clones, constructors that would just copy the attributes of one object and create another, and add that in the second list, but every time i change the second list, the first one changes also. So, how could i just have 2 lists, that at first have the same items, in the same order, but themselves are totally different? Just adding the each item from the first list to the second doesn't work.. Example:

ArrayList<Object> list1 = new ArrayList<Object>():
list1.add(obj1);
list1.add(obj2);
ArrayList<Object) list2 = new ArrayList<Object>(list1);
list2.remove(0);

What i want is to be able to modify list2 (list2.remove(0)) but i need list1 to remain unmodified, so list1.size()!=list2.size(). Also: i need that obj1 from list1 to be the same to obj1 from the list2.

È stato utile?

Soluzione

but if i change the second list in any way, the first list should remain the same

So just copy the references into a new list. There are constructors for that.

but if i change an item from the second list, it should also modify in the first.

See above.

I've tried using clones, constructors that would just copy the attributes of one object and create another and add that in the second list

That's what you don't want to do. You want the original references in both lists.

but every time i change the second list, the first one changes also

Not possible. If you did want you describe, the two lists and their contents are completely independent. In any case this is the wrong approach. This also constitutes dereferencing the original objects, which you said you didn't want to do.

Just adding each item from the first list to the second doesn't work

Yes it does. I suggest you have confused yourself with all these alternatives.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top