Integer 值判斷相等
案例:
public class Test {public static void main(String[] args) {Integer a = 127;Integer b = 127;System.out.println("a == b :"+ (a == b));System.out.println("a.equals(b):"+a.equals(b));String x = "127";String y = "127";System.out.println("Integer.valueOf(x) == Integer.valueOf(y) :" + (Integer.valueOf(x) == Integer.valueOf(y)));System.out.println("Integer.valueOf(x).equals(Integer.valueOf(y)):"+Integer.valueOf(x).equals(Integer.valueOf(y)));System.out.println("====================================================================");Integer a1 = 128;Integer b1 = 128;System.out.println("a1 == b:"+(a1 == b1));System.out.println("a.equals(b):"+a.equals(b1));String x1 = "128";String y1 = "128";System.out.println("Integer.valueOf(x1) == Integer.valueOf(y1) :" + (Integer.valueOf(x1) == Integer.valueOf(y1)));System.out.println("Integer.valueOf(x1).equals(Integer.valueOf(y1)):"+Integer.valueOf(x1).equals(Integer.valueOf(y1)));}
}
日志打印:
a == b :true
a.equals(b):true
Integer.valueOf(x) == Integer.valueOf(y) :true
Integer.valueOf(x).equals(Integer.valueOf(y)):true
====================================================================
a1 == b:false
a.equals(b):false
Integer.valueOf(x1) == Integer.valueOf(y1) :false
Integer.valueOf(x1).equals(Integer.valueOf(y1)):true
通過案例發現,值為127不管是 Integer 還是 String 類型,== 和 equals 都能比較成功。128與類型無關,與比較的方法有關。
equals
通過查看源碼發現 Integer 重寫的 equals、hashCode 方法,所以使用 equals 方法比較大小母庸質疑為 true.
/*** Returns a hash code for this {@code Integer}.** @return a hash code value for this object, equal to the* primitive {@code int} value represented by this* {@code Integer} object.*/@Overridepublic int hashCode() {return Integer.hashCode(value);}/*** Returns a hash code for a {@code int} value; compatible with* {@code Integer.hashCode()}.** @param value the value to hash* @since 1.8** @return a hash code value for a {@code int} value.*/public static int hashCode(int value) {return value;}/*** Compares this object to the specified object. The result is* {@code true} if and only if the argument is not* {@code null} and is an {@code Integer} object that* contains the same {@code int} value as this object.** @param obj the object to compare with.* @return {@code true} if the objects are the same;* {@code false} otherwise.*/public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false;}
==
127和127比較返回true,128和128比較返回false,有點出乎意料,主要是因為我們使用了慣用思維“以為/覺得”他們相等,沒有經過認證。Integer a = 127; 是自動裝箱會調用Interger.valueOf(int)方法;
public static Integer valueOf(String s) throws NumberFormatException {return Integer.valueOf(parseInt(s, 10));}public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
默認 IntegerCache.low 是-127,Integer.high是128,如果在這個區間內,他就會把變量i當做一個變量,放到內存中;但如果不在這個范圍內,就會去new一個 Integer 對象,所以使用 “==” 比較127返回true,比較128返回 false。