java - ArrayList 实际存储什么 - 对对象或实际对象的引用?

标签 java arraylist

假设我的代码是这样的:

ArrayList list = new ArrayList();
Student s = new Student();    // creating object of Student class

myList.add(s);      // Here am confused ...

/* myList contains just the reference variable to the Student object, OR

   myList contains the actual Student object (memory allocation for name, rollNo etc)  ??   
*/

简而言之,当使用 add() 将对象添加到 ArrayList 时:

ArrayList 是“对象引用”列表还是“实际对象”列表???

最佳答案

在 Java 中,您永远不会传递实际对象。你总是在处理一个引用,它本质上只是一个指向内存中存储对象的位置的地址。

由于您从不使用实际对象,因此 ArrayLists 包含对存储在其他地方(内存中称为堆的位置)的对象的引用数组。

关于java - ArrayList 实际存储什么 - 对对象或实际对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18855639/

相关文章:

java - 无法正确返回 arraylist 对象

java - 代码复杂的Subject.doAs

java - 随机访问文件问题

java - 我的 for 循环没有指向正确的属性

java - 如果对象的一个​​值重复,则从 ArrayList 中删除

java - 使用for循环java将多个对象添加到ArrayList

java - 同步和合并消息/数据流

java - 使用 @MapsId 保留 @OneToOne 子实体会在 Hibernate 中抛出 "error:detached entity passed to persist"

java - 为 2D 点的 ArrayList 实现方法 add(int,int)

java - 如何在java中使用ArrayList制作XY折线图