Integer类认识
Integer类有一个缓存,他会缓存介于-128-127之间的整数。
首先看一段代码(使用JDK 5),如下:
public class Test { public static void main(String[] args) { Integer i1 = 127; Integer i2 = 127; if (i1 == i2) System.out.println("Equal!"); else System.out.println("Not equal!"); } } import java.io.PrintStream; public class Test { public Test() { } public static void main(String args[]) { Integer i1 = Integer.valueOf(128); Integer i2 = Integer.valueOf(128); Integer i3 = Integer.valueOf(128); if(i1 == i2) System.out.println("i1 == i2 is true!"); else System.out.println("i1 == i2 is false!"); if(i1.intValue() >= i2.intValue()) System.out.println("i1 >= i2 is true!"); else System.out.println("i1 >= i2 is false!"); if(i1 == i3) System.out.println("i1 == i3 is true!"); else System.out.println("i1 == i3 is false!"); } } import java.io.PrintStream; public class Test { public Test() { } public static void main(String args[]) { Integer i1 = Integer.valueOf(128); Integer i2 = Integer.valueOf(128); Integer i3 = Integer.valueOf(128); if(i1 == i2) System.out.println("i1 == i2 is true!"); else System.out.println("i1 == i2 is false!"); if(i1.intValue() >= i2.intValue()) System.out.println("i1 >= i2 is true!"); else System.out.println("i1 >= i2 is false!"); if(i1 == i3) System.out.println("i1 == i3 is true!"); else System.out.println("i1 == i3 is false!"); } } import java.io.PrintStream; public class Test { public Test() { } public static void main(String args[]) { Integer i1 = Integer.valueOf(128); Integer i2 = Integer.valueOf(128); Integer i3 = Integer.valueOf(128); if(i1 == i2) System.out.println("i1 == i2 is true!"); else System.out.println("i1 == i2 is false!"); if(i1.intValue() >= i2.intValue()) System.out.println("i1 >= i2 is true!"); else System.out.println("i1 >= i2 is false!"); if(i1 == i3) System.out.println("i1 == i3 is true!"); else System.out.println("i1 == i3 is false!"); } } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; //这个主意下,Cache 缓存了-128~127的值 } return new Integer(i); } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; //这个主意下,Cache 缓存了-128~127的值 } return new Integer(i); } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; //这个主意下,Cache 缓存了-128~127的值 } return new Integer(i); }