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; } }
反编译的字节码设计
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); }