[英]Strange Logical Error in Java Code
interface New<T> {
boolean func(T n, T v);
}
class MyFunc<T>{
T val;
MyFunc(T val){
this.val = val;
}
void Set(T val){
this.val = val;
}
T Get(){
return val;
}
boolean isEqual(MyFunc<T> o){
if(val == o.val) return true;
return false;
}
public class Main {
static <T> boolean check(New<T> n , T a, T b){
return n.func(a,b);
}
public static void main(String args[]){
int a = 321;
MyFunc<Integer> f1 = new MyFunc<Integer>(a);
MyFunc<Integer> f2 = new MyFunc<Integer>(a);
boolean result;
//f2.Set(f1.Get()); //if i uncomment this line result become true
System.out.println(f1.val + " " + f2.val);
System.out.println();
result = check(MyFunc::isEqual, f1, f2);
System.out.println("f1 isEqual to f2: " + result);
}
}
Why result is false when 'a'
is used in both f1
and f2
? 当在f1
和f2
使用'a'
时,为什么结果是假的? Why result is true when f2.Set(f1.Get());
为什么f2.Set(f1.Get());
时结果为真f2.Set(f1.Get());
is uncommented? 没有注释? Please explain me where I am making mistake. 请解释我在哪里弄错了。
In the .isEquals()
method you're comparing tho wrapper objects with the ==
operator, which compares the objects references if those are not within the Integer
internal cache. 在.isEquals()
方法中,您将使用==
运算符比较包装器对象,如果这些对象引用不在Integer
内部缓存中,则会比较对象引用。
Since 321
is out of the Integer
cache, the ==
operator returns false
, because the references are different ( f1
refers to different memory address than f2
). 由于321
不在Integer
缓存中,因此==
运算符返回false
,因为引用不同( f1
指的是与f2
不同的内存地址)。
When you explicitly set the references to be equal (with f2.Set(f1.Get())
), then it's not surprising the program outputs true
. 当您明确地将引用设置为相等(使用f2.Set(f1.Get())
)时,程序输出为true
并不奇怪。
If you set a
to something between -128
and 127
, the program will output true
. 如果将a
设置a
-128
到127
之间的某个值,程序将输出true
。
a
is auto boxed to Integer
and for int a = 321;
a
自动装箱为Integer
, int a = 321;
you will have two different Objects
for f1
and f2
. 对于f1
和f2
你将有两个不同的Objects
。
FOR EXAMPLE 例如
Integer a1 = new Integer(321);
Integer a2 = new Integer(321);
and for a1 == a2
you will have false
because ==
compare reference instead of value you should use equals
method to check value in your isEqual
method. 并且对于a1 == a2
你将得到false
因为==
比较引用而不是值,你应该使用equals
方法来检查isEqual
方法中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.