1 public enum VirusCheckRes { 2 3 UNKNOW(0), SAFE(1), HIGH_RISK(2), MEDIUM_RISK(3), LOW_RISK(4); 4 5 private Integer status; 6 private VirusCheckRes(Integer status){ 7 this.status = status; 8 } 9 public Integer getStatus() { 10 return this.status; 11 } 12 public void setStatus(Integer status) { 13 this.status = status; 14 } 15 16 }
在作以下判斷時:html
if (VirusCheckRes.SAFE.getStatus() == virusRes)
public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }
public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Integer a1 = new Integer(4); Integer a2 = new Integer(4); System.out.println(a1 == a2); //false Integer i1 = 13; Integer i2 = 13; System.out.println(i1 == i2); //true Integer i3 = 128; Integer i4 = 128; System.out.println(i3 == i4); //false Integer i5 = Integer.valueOf(3); Integer i6 = Integer.valueOf(3); System.out.println(i5 == i6); //true Integer i7 = Integer.valueOf(128); Integer i8 = Integer.valueOf(128); System.out.println(i7 == i8); //false } }
a1==a2 -> false能夠理解,跟個人錯誤同樣java
i1==i2 -> true 就有點意思了設計模式
接下來數組
i3 = i4 -> false(與i1=i2有什麼區別?)ide
i5 == i6 -> true 什麼鬼ui
i7==i8 -> falsethis
根據a1 != a2 ,i1 == i2, i5 == i6,能夠看出,自動裝箱用的應該是valueOf方法,而非構造方法,從反編譯獲得的字節碼中也能夠證實這點spa
源碼爲:.net
public class Main { public static void main(String[] args) { Integer i = 10; int n = i; } }
反編譯的字節碼設計
一樣能夠看出,拆箱時,用的是intValue方法public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }
private static class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128; // high value may be configured by property int h = 127; if (integerCacheHighPropValue != null) { // Use Long.decode here to avoid invoking methods that // require Integer's autoboxing cache to be initialized int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} }
// value of java.lang.Integer.IntegerCache.high property (obtained during VM init) private static String integerCacheHighPropValue;
從代碼中能夠看出,IntegerCache是Integer中的內部類,裏面定義了兩個屬性,high,cache,其中high在static塊中給出了賦值,若是配置integerCacheHighPropValue的話,默認的high是127,low=-128
public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }