跟我走..比較整數值在Java中,行爲怪異
Integer x = 23;
Integer y = 23;
if (x == y)
System.out.println("what else"); // All is well as expected
else
System.out.println("...");
雖然
Integer x = someObject.getIndex();
Integer y = someOtherObject.getSomeOtherIndex();
if (x == y)
System.out.println("what else");
else
System.out.println("..."); // Prints this
嗯...我儘量鑄造爲int
int x = someObject.getIndex();
int y = someOtherObject.getSomeOtherIndex()
if (x == y)
System.out.println("what else"); // works fine
else
System.out.println("...");
是他們都整型?
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
你們認爲什麼?什麼會解釋這樣的事情?
可能重複【如何=運算符和==操作符在Java中?](http://stackoverflow.com/questions/9824053/how-operator-and-operator-works-in-java) – assylias 2012-04-03 22:08:07
getIndex();和getSomeOtherIndex()是做什麼的? – 2016-02-17 12:08:42
[爲什麼128 == 128返回false,但是127 == 127在轉換爲Integer包裝器時返回true?](https://stackoverflow.com/questions/1700081/why-does-128-128-return- false-127-127-return-true-when-convert-to-integ) – Tom 2018-02-05 16:17:28