2016-01-20 25 views
1

当我将一个2MB对象Foo bar转换为Collection<Foo>时,现在有4MB的Foo s在内存中还是只有2MB?添加项目到集合的实际内存影响

例如

Foo twoMBObject = new Foo(); 
ArrayList<Foo> bax = new ArrayList<>(); 
bax.add(twoMBObject); 

/* Do we now have bax-twoMBObject & twoMBObject or just twoMBObject 
and a pointer to twoMBObject in the list? */ 

编辑
我有一个很难弄清楚如果建议重复的问题实际上是重复的。虽然接受的答案不能回答这个问题,但提供的答案之一的确如此。我不知道如何在这里继续。

+2

集合包含对象的引用。所以2 MB内存 – algor

+3

不用担心,它只有2 MB。您添加对列表的引用,而不是克隆的对象 – AdamSkywalker

+3

[是否将附加项/删除项重新分配给内存?](http://stackoverflow.com/questions/34617193/does-appending-removing-entries -java-list-reallocate-memory) – Raedwald

回答

4

您有2MB,因为您只需添加对该对象的引用,而不要创建该对象的副本。

一个简单的方法来测试这是通过使用Runtime.getRuntime().totalMemory()方法。例如:

public static void main(String[] args) { 
    Byte[] b = new Byte[1000]; 
    Runtime runtime = Runtime.getRuntime(); 

    long allocatedMemory = runtime.totalMemory() - runtime.freeMemory(); 
    System.out.println(allocatedMemory); 

    List<Byte[]> collection = new ArrayList<>(); 
    collection.add(b); 

    allocatedMemory = runtime.totalMemory() - runtime.freeMemory(); 
    System.out.println(allocatedMemory); 
} 
+1

我只是看着文档。它是。感谢您的更正: –

+0

只要我发现这是否是重复问题,我就会接受此问题。 – nukeforum

+0

@nukeforum很高兴我可以帮忙;) –

2

现在在那里FOOS的4MB内存或只有2MB?

2 MB,因为当你做new Foo(),空间2MB分配并返回到对象的引用。现在,当你bax.add(twoMBObject);你基本上是添加对ArrayList的引用,而不是创建一个“新”对象。

如果您尝试使用参考twoMBObject更改对象中的内容,您将会看到对象中反映的更改也会添加到ArrayList。这证明它是同一个对象。

相关问题