Walk với tôi ..So sánh giá trị Integer trong Java, hành vi kỳ lạ
Integer x = 23;
Integer y = 23;
if (x == y)
System.out.println("what else"); // All is well as expected
else
System.out.println("...");
Trong khi
Integer x = someObject.getIndex();
Integer y = someOtherObject.getSomeOtherIndex();
if (x == y)
System.out.println("what else");
else
System.out.println("..."); // Prints this
Hmm ... Tôi cố gắng đúc để int
int x = someObject.getIndex();
int y = someOtherObject.getSomeOtherIndex()
if (x == y)
System.out.println("what else"); // works fine
else
System.out.println("...");
Họ có cả hai Số nguyên?
System.out.println(x.getClass().getName()); // java.lang.Integer
System.out.println(y.getClass().getName()); // java.lang.Integer
System.out.println(someObject.getIndex()); // java.lang.Integer
System.out.println(someOtherObject.getSomeOtherIndex()); // java.lang.Integer
Các bạn nghĩ sao? Điều gì sẽ giải thích một cái gì đó như thế này?
thể trùng lặp của [Làm thế nào = điều hành và == nhà điều hành các công trình trong Java ?] (http://stackoverflow.com/questions/9824053/how-operator-and-operator-works-in-java) – assylias
'getIndex();' và 'getSomeOtherIndex()' làm gì? –
Có thể trùng lặp [Tại sao 128 == 128 trả về false nhưng 127 == 127 trả về true khi chuyển đổi thành Trình bao bọc Integer?] (Https://stackoverflow.com/questions/1700081/why-does-128-128-return- false-but-127-127-return-true-when-conversion-to-integ) – Tom