Integer进行比较计算的特殊情景
@Test
public void testInteger ( ) {
int i = 10 ;
Integer ii = 10 ;
Integer iii = 10 ;
System. out. println ( i == ii) ;
System. out. println ( ii == iii) ;
int j = 128 ;
Integer jj = 128 ;
Integer jjj = 128 ;
System. out. println ( j == jj) ;
System. out. println ( jj == jjj) ;
}
对于int和Integer的对比,由于存在自动拆箱机制,所以Integer会被转换成int,可以使用==号来比较是否相等 对于两个Integer的比较,就要分情况了
使用字面量赋值,也就是如Integer i = 100; 由于存在整数缓存机制,所以-127到127之间的Integer对象都会被缓存起来.所以在这个范围内,使用字面量赋值的两个Integer是可以使用==来判断相等的. 使用new创建Integer对象,对于这种创建方式,无论对象是否在-127到127之间,得到的Integer对象必然不是同一个对象.无法使用==来判断是否相等 使用Integer.valueOf;通过这种方法创建的对象与直接使用字面量赋值是一致的,只要不超过-127 到 127 则使用缓存,超过了就使用new来创建对象. Integer i = 10 ;
Integer ii = Integer. valueOf ( 10 ) ;
Integer iii = new Integer ( 10 ) ;
System. out. println ( i == ii) ;
System. out. println ( ii == iii) ;