我想提高我对编程语言(尤其是 Java)内存模型的了解,所以我有一个问题。
这是非常简单的代码:
// Allocating memory in heap for SimpleObject's instance
// Creating reference to this object with name so1
SimpleObject so1 = new SimpleObject();
// Allocating memory in heap for array of 10 references to SimpleObject's objects
// Now I know, that array stores only references to the objects
// (Previously I thought that array stores objects)
// Then we create reference to this array with name soArray
SimpleObject[] soArray = new SimpleObject[10];
现在的问题:
// What is going on here?
soArray[0] = so1;
// object so1 had been really moved to memory area of soArray?
// And so1 reference have been updated to new memory address?
// Or we just had assigned so1 object's reference to soArray[0] element?
// Or so1 object had been copied to the soArray[0]?
// Then original so1 object has been deleted and all links to it had been updated?
如果您知道它在其他语言中的工作原理,例如(C、C++、C# 或其他),请回答,我会很高兴知道。
大家都知道,ArrayList 可以比 LinkedList 快,因为数组的元素可以存储在 CPU 缓存中,而如果我们使用 LinkedList,CPU 每次都必须从 RAM 中获取下一个对象。
那么,如果一开始我在堆中创建了对象,然后才将对象放入数组中,它怎么能工作呢?
UPD:谢谢你们,现在我了解了数组是如何工作的,但是以这种方式在 CPU 缓存中缓存数组呢?