我遇到了一个情况,我很困惑。请帮帮我。 假设我有这样的代码。
MyClass obj1 = null;
List<MyClass> testList = new ArrayList<MyClass>();
testList.add(obj1);//after this line of code, testList will have a "null" at first node
obj1 = new MyClass();//after this line of code, testList still have a "null"
//at first node...
//What I want is that testList's first node will become a new
//MyClass object
这是我理解的步骤(可能不正确......):
- obj1 存储指向任何内容的指针...
- testList存储指向保存“new ArrayList()”的内存的指针
- testList将obj1的指针添加到其集合中。
- obj1 存储指向“new MyClass()”的指针
- 因此,testList中的obj1应该自动指向“new MyClass()”
抱歉,我是编程新手...... 如有任何帮助,我们将不胜感激!
最佳答案
这里解释了为什么 testList 在这段代码之后的第一个节点仍然有一个“null”
testList.add(obj1);//after this line of code, testList will have a "null" at first node
obj1 = new MyClass();//after this line of code, testList still have a "null"
//at first node...
//What I want is that testList's first node will become a new
//MyClass object
第 1 步
MyClass obj1 = null;
该行为 MyClass 引用变量(位持有者 供引用),但不会创建实际的 Myclass 对象。
第 2 步
List<MyClass> testList = new ArrayList<MyClass>();
创建一个列表testList,它可以保存MyClass类型的对象
第3步
testList.add(obj1);//after this line of code, testList will have a "null" at first node
testList 第一个节点现在将引用 null 但不是 MyClass 对象。
第 4 步
obj1 = new MyClass();
在堆上创建一个新的 MyClass 对象,并将新创建的 MyClass 对象分配给引用变量 obj1。
那么现在列表如何更新它仍然持有 null 但不是 MyClass 对象。
现在如果你想让testList的第一个节点成为一个新的MyClass对象
然后在 obj1 = new MyClass();
testList.set(0, obj1);
现在完整的代码是
MyClass obj1 = null;
List<MyClass> testList = new ArrayList<MyClass>();
testList.add(obj1);//after this line of code, testList will have a "null" at first node
obj1 = new MyClass();
testList.set(0, obj1);
根据我的理解,这就是您的问题。
关于java - Java 对象引用是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16089642/