Reputation: 33
See the following code:
list and anotherList have same object, I wonder if the memory will become two copies.
public static void main(String[] args) {
List<Test> list = new ArrayList<>();
list.add(new Test(10));
List<Test> anotherList = new ArrayList<>();
anotherList.add(list.get(0));
anotherList.get(0).a = 15;
System.out.println(list.get(0).a);
}
static class Test{
public int a;
Test(int a){
this.a = a;
}
}
Upvotes: 2
Views: 733
Reputation: 2656
Not by much, just the necessary parts to the list inner workings to add the new item.
Java uses References, so when an instance is added to two list you are just adding the reference (effectively an id) to the instance not a copy of it.
Which also means that if you change it in one list it also changes in the other.
Upvotes: 5
Reputation: 37506
list and anotherList have same object, I wonder if the memory will become two copies.
It will not become two copies, but you will have two references. The cost of a reference is 64bits on a 64bit CPU, so not much. (64bits here is the size of the memory address).
One thing to bear in mind here is that if you do this sort of thing you run the risk of leaving stray, live references to the object around. That will end up eating up memory because those live references will prevent the object from being garbage collected. If you make references like that to one object among multiple collections, you need to have a strategy for ensuring the object doesn't live past your need.
Upvotes: 2