Java对象引用如何工作? [英] How does Java Object reference works?
问题描述
我遇到了一种情况,我感到非常困惑.请帮帮我. 假设我有这样的代码.
I running to a situation and I am very confused. Please help me out. Let's say I have a code like this.
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
以下是我理解的步骤(可能不正确...):
Here is the steps in my understanding (probably incorrect...):
- obj1 存储指向无内容的指针...
- testList 存储指向保存"new ArrayList()"的内存的指针
- testList 在其集合中添加 obj1 的指针.
- obj1 存储指向新MyClass()"的指针
- 因此, testList 中的 obj1 应该自动指向新的MyClass()"
- obj1 stores the pointer that points to nothing...
- testList stores the pointer that points to the memory that holds the "new ArrayList()"
- testList add the pointer of obj1 in its collection.
- obj1 stores the pointer that points to a "new MyClass()"
- therefore, the obj1 in the testList should automatically points to the "new MyClass()"
对不起,我是编程新手. 感谢您的帮助!
Sorry I am new to programming... Any help is appreciated!
推荐答案
这就是为什么testList在这些代码之后的第一个节点上仍为"null"的原因所在
Here is the explination why testList still have a "null" at first node after these piece of code
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对象.
This line creates space for the MyClass reference variable (the bit holder for a reference value), but doesn't create an actual Myclass object.
第2步
List<MyClass> testList = new ArrayList<MyClass>();
创建一个列表 testList ,该列表可以容纳 MyClass 类型的对象
A list is created testList which can hold objects of MyClass types
第3步
testList.add(obj1);//after this line of code, testList will have a "null" at first node
testList的第一个节点现在将引用一个空值,而不是MyClass对象.
testList first node will now refer to an null But not an MyClass Object.
第4步
obj1 = new MyClass();
在堆上创建一个新的MyClass对象,并将新创建的MyClass对象分配给引用变量obj1.
Creates a new MyClass object on the heap and Assigns the newly created MyClass object to the reference variable obj1.
所以现在如何更新列表,它仍然保留一个null而不是MyClass对象.
So now how will the list gets updated it is still holding an null But not an MyClass Object.
现在,如果您要使testList的第一个节点成为新的 MyClass 对象
So now if you want to make testList's first node to become a new MyClass object
然后在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对象引用如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!