gpt4 book ai didi

java - 学校的一个小例子遇到了麻烦

转载 作者:行者123 更新时间:2023-12-01 17:28:47 25 4
gpt4 key购买 nike

该示例来自类(class),用于比较 java 中的两个对象:

public class Complex {

...

public boolean equals (Object obj) {
if (obj instanceof Complex) { // if obj is "Complex" (complex number)
Complex c = (Complex) obj // No idea
return (real == c.real) && (imag == c.imag);
// I'm guessing real means [this].real
}
return false;
}
}

所以,我的问题是:“这是什么意思:Complex c = (Complex) obj 实际上意味着什么”?

我还使用过 python 和 c++,java 对我来说是新的。

最佳答案

查看我的内联评论。

    public class Complex {

...

public boolean equals (Object obj) {
if (obj instanceof Complex) { // you first need to check whetever the obhect passed to the equal method is indeed of type "Complex" because i guess what you want here is to compare two Complex objects.
Complex c = (Complex) obj // If the object is complex then you need to treat it as complex so cast it to Complex type in order to compare the "real" and "imag" values of the object.
return (real == c.real) && (imag == c.imag);
// I'm guessing real means [this].real
// yes, it does.
}
return false;
}

}

了解有关类型转换的更多信息,请访问 here

您还可以检查装箱和拆箱概念。

希望这有帮助,丹

关于java - 学校的一个小例子遇到了麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987640/

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