gpt4 book ai didi

Java:总是具有相同内容的对象?

转载 作者:行者123 更新时间:2023-12-02 12:58:56 25 4
gpt4 key购买 nike

我想用一个例子来描述我的问题:

Base.java:

public class Base {

//NO annotations
public AnyClass anyObj;

public Base(){}
}

DerivedOne.java:

public class DerivedOne extends Base{

@SomeAnnotionsOne
public AnyClass anyObjWithAnnotations;

public DerivedOne (AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}

DerivedTwo.java:

public class DerivedTwo extends Base {

//These annoations differ from @SomeAnnotionsOne
@SomeAnnotionsTwo
public AnyClass anyObjWithAnnotations;

public Derived_Two(AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}

所以我只想 anyObjWithAnnotations 始终等于 anyObj

主要示例:

public static void main(String[] args){
DerivedOne derivedObj = new DerivedOne(new AnyClass());
derivedObj.anyObj = null;

if(derivedObj.anyObjWithAnnotations == null){
System.out.println("anyObjWithAnnotations : is null");
}
}

没有打印任何内容。 anyObjnullanyObjWithAnnotations 不是。

我的问题:

是否有可能 anyObj 始终与 anyObjWithAnnotations 相同??

因此,即使我将其中一个设置为 null 或使用 new 创建 AnyClass 的新实例,另一个变量也应该具有相同的值新内容。

编辑:

更改了整个示例以澄清问题。

最佳答案

您可以使用下面的代码,其中我仅创建对象 1 次,然后将其引用分配给第二个对象。这样,如果一个对象中的值发生更改,例如 t1,它也会反射(reflect)到 t2 中。

    class Test {
private int val;

public Test(int val) {
this.val = val;
}

public int getVal() {
return val;
}

public void setVal(int val) {
this.val = val;
}
}
public class TestSame {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2=t1;
System.out.println(t1.getVal());
System.out.println(t2.getVal());

t1.setVal(20);

System.out.println(t1.getVal());
System.out.println(t2.getVal());

}
}

操作:-

10
10
20
20

您还可以检查 t1 和 t2 是否具有相同的哈希码值

  System.out.println("t1 hashcode "+ t1.hashCode());
System.out.println("t2 hashcode "+ t2.hashCode());

关于Java:总是具有相同内容的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343223/

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