当相同的对象添加到两个列表中时,内存会增加吗?

huangapple go评论80阅读模式
英文:

Does the memory increase when the same object is added to two lists?

问题

看下面的代码:

listanotherList 指向相同的对象,我想知道内存是否会变成两份拷贝。

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;
    }
}
英文:

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&lt;Test&gt; list = new ArrayList&lt;&gt;();
    list.add(new Test(10));
    
    List&lt;Test&gt; anotherList = new ArrayList&lt;&gt;();
    
    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;
    }
}

答案1

得分: 4

不多,只需将必要的部分添加到列表的内部工作以添加新项目。

Java使用引用,因此当将实例添加到两个列表时,实际上是在添加实例的引用(实际上是一个标识),而不是实例的副本。

这也意味着,如果在一个列表中对其进行更改,它也会在另一个列表中更改。

英文:

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.

答案2

得分: 1

list和anotherList引用相同的对象,我想知道内存会不会变成两个副本。

不会变成两个副本,但会有两个引用。在64位CPU上,一个引用的成本为64位,所以不多。(这里的64位是内存地址的大小)。

需要记住的一件事是,如果你这样做,你有可能会留下零散的、活动的对象引用。这将最终消耗掉内存,因为这些活动引用将阻止对象被垃圾回收。如果你在多个集合中对一个对象进行这样的引用,你需要有一种策略来确保对象在你的需求过后不会继续存在。

英文:

> 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.

huangapple
  • 本文由 发表于 2020年10月26日 20:14:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64536926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定