将同一个对象添加到两个列表时,内存会增加吗?
Does the memory increase when the same object is added to two lists?
见以下代码:
list和anotherList有相同的object,不知道内存会不会变成两份
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;
}
}
不多,只是列表内部工作的必要部分以添加新项目。
Java 使用引用,所以当一个实例被添加到两个列表时,您只是将引用(实际上是一个 id)添加到实例而不是它的副本。
这也意味着如果您在一个列表中更改它,它也会在另一个列表中更改。
list and anotherList have same object, I wonder if the memory will become two copies.
它不会变成两份,但你会有两个参考。参考的成本是 64 位在 64 位 CPU 上,所以并不多。 (这里的64bits是内存地址的大小)
这里要记住的一件事是,如果您执行此类操作,您 运行 有可能会遗漏对周围对象的实时引用。这最终会耗尽内存,因为那些实时引用会阻止对象被垃圾回收。如果您对多个集合中的一个对象进行类似的引用,则需要制定一种策略来确保该对象不会超出您的需要。
见以下代码:
list和anotherList有相同的object,不知道内存会不会变成两份
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;
}
}
不多,只是列表内部工作的必要部分以添加新项目。
Java 使用引用,所以当一个实例被添加到两个列表时,您只是将引用(实际上是一个 id)添加到实例而不是它的副本。
这也意味着如果您在一个列表中更改它,它也会在另一个列表中更改。
list and anotherList have same object, I wonder if the memory will become two copies.
它不会变成两份,但你会有两个参考。参考的成本是 64 位在 64 位 CPU 上,所以并不多。 (这里的64bits是内存地址的大小)
这里要记住的一件事是,如果您执行此类操作,您 运行 有可能会遗漏对周围对象的实时引用。这最终会耗尽内存,因为那些实时引用会阻止对象被垃圾回收。如果您对多个集合中的一个对象进行类似的引用,则需要制定一种策略来确保该对象不会超出您的需要。