java - Java 对象引用是如何工作的?

标签 java object pointers reference

我遇到了一个情况,我很困惑。请帮帮我。 假设我有这样的代码。

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

这是我理解的步骤(可能不正确......):

  1. obj1 存储指向任何内容的指针...
  2. testList存储指向保存“new ArrayList()”的内存的指针
  3. testListobj1的指针添加到其集合中。
  4. obj1 存储指向“new MyClass()”的指针
  5. 因此,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/

相关文章:

java - 如何使用 Java 主类中创建的对象将值传递给方法

c语言与指针的一些疑惑

c++ - 在函数中获取排序数组和值并将该值放在正确的位置

Java 正则表达式 ReplaceAll 与分组

java - AWS Lambda 中的 Oracle 数据库连接

Java链表与对象 - 空指针异常

c - 双向链表释放内存 valgrind 错误

c# - iOS 中没有 bcrypt 实现...可以使用其他语言,创建静态库吗?

java - 安卓 : Entries cannot be protected with passwords

javascript - while循环值测试