gpt4 book ai didi

java - 我不知道为什么 A 的对象最后也被打印

转载 作者:行者123 更新时间:2023-11-30 06:06:15 24 4
gpt4 key购买 nike

有人可以解释一下为什么我会得到这个输出

package code;
import java.util.ArrayList;
class A {
}
class B extends A {
}
class C extends B {
}
public class ThreadDemo {
public static void main(String[] args) {
ArrayList<A> x = new ArrayList<A>();
ArrayList a = new ArrayList();
x.add(new A());
a = x;
a.add(new B());
ArrayList b = a;
ArrayList<C> c = (ArrayList<C>) b;
c.add(new C());
a.add(new A()); // I am not sure why object of A is also getting printed at the last
for (Object obj : c) {
System.out.println(obj + " class Name " + obj.getClass().getName());
}
}
}

输出:

----------
code.A@7852e922 class Name code.A
----------
code.B@4e25154f class Name code.B
----------
code.C@70dea4e class Name code.C
----------
code.A@5c647e05 class Name code.A
----------

最佳答案

ac 是同一个对象。我们看一下相关的代码行:

ArrayList a = new ArrayList(); // a is created
ArrayList b = a; // b holds a reference to the same object
ArrayList<C> c = (ArrayList<C>) b; // and so does c

因此,每当您向 c 添加一个对象时,它也会出现在 a 中(因为,如上所述,它们是同一个对象!)。

关于java - 我不知道为什么 A 的对象最后也被打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44604283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com