boolean result;
Integer a = 99;
Integer b = 99;
result = a == b;
System.out.println("Integer a=99 is == Integer b = 99:" + result);
Integer c = 128;
Integer d = 128;
result = c == d;
System.out.println("Integer c=128 is == Integer d=128:" + result);
Integer e = 99;
Integer f = new Integer(99);
result = e == f;
System.out.println("Integer e=99 is == Integer f=new Integer(99):" + result);
Integer g = 128;
Integer h = new Integer(128);
result = g == h;
System.out.println("Integer g=128 is == Integer h = new Integer(128): " + result);
Integer i = new Integer(99);
Integer j = new Integer(99);
result = i == j;
System.out.println("Integer i=new Integer(99) is == j=new Integer(99):" + result);
Integer k = 128;
int l = 128;
result = k == l;
System.out.println("Integer k = 128 is == int 1 = 128:" + result);
结果
Integer a=99 is == Integer b = 99:true
Integer c=128 is == Integer d=128:false
Integer e=99 is == Integer f=new Integer(99):false
Integer g=128 is == Integer h = new Integer(128): false
Integer i=new Integer(99) is == j=new Integer(99):false
Integer k = 128 is == int 1 = 128:true
对于Integer a = 99的这种直接赋值,jvm会编译优化成Interger.valueOf(99)。
cache区间-128到127
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
String a = "this";
String b = "this";
System.out.println("字符串:" + (a == b));//放在常量池
String c = new String("is");
String d = new String("is");
System.out.println("new:" + (c == d));
String e = new String("a").intern();//将对象放进常量池里
String f = new String("a").intern();
System.out.println("new-intern:" + (e == f));
String g = new String("test");
String h = new String("test");
System.out.println("equals:" + g.equals(h));
结果
字符串:true
new:false
new-intern:true
equals:true
String类的设计,也借鉴了Integer的cache缓存,java的设计之初就是为了节省内存的,所String对象也是有常量池的。
通过String.intern()这种方式,是强制将对象放到字符串常量池里,所以通过这种方式,对于同一个字符串,返回的结果一定是true。这里要注意string.intern)也不能滥用,因为字符串常量表是用map来维护的,而且map是有固定容量的,所以对象如果太多的话, map中每个index下的值会退化成一个比较长的链表,查询效率大大下降。所以使用intern的字符串对象太多的话,效率反而不高。