你是不是经常在做题的时候,会遇到这种类型的题:
- int i1 = 128;
Integer i2 = 128;
Assert.assertTrue(i1 == i2);
但是你又对 int 和 Integer 的区别不是那么的清晰
小伙伴们,你们的福利来了,下面我将为你详细叙述两者的区别:
1、int 和 Integer 在内存中的分配:
- 1、int 类型 赋一个整数值,不管大小,都是在常量池中查找;如果有,返回引用,如果没有,创建再返回引用。
- 2、Integer 类型 赋一个整数值,-128到127范围内的值都是先查找常量池;如果有,直接返回这个引用,如果没有,则在常量池中创建,再返回这个引用。再范围外,则再堆中创建一个Integer 对象,对象的属性 value 指向常量池中的常量。
- 3、Integer 和 int 类型比较,会将Integer类型对象进行自动拆箱,实际上就是 Integer 中的value属性和int的比较,所以不管是否在-128到127范围,只要值相等就相等。
- 4、Integer 和 Integer 比较,要看这两个 Integer 是指向的常量池对象,还是堆中的对象。所以只要有一个是通过 new Integer() 的方式赋值的,那就肯定不相等。而如果都是使用常量赋值的,如 Integer i = 10;因为在-128到127范围内,都是指向常量池对象,所以相等,如果超出范围赋值,就不相等。
2、上代码:
// 基本数据类型==比较都是比较字面量
@Test
public void test1_1(){
// 测试通过
int i1 = 10;
int i2 = 10;
Assert.assertTrue(i1 == i2);
}
@Test
public void test1_2(){
// 测试通过
int i1 = 128;
int i2 = 128;
Assert.assertTrue(i1 == i2);
}
@Test
public void test1_3(){
// 测试通过
int i1 = 128;
char c = (char) 128;
Assert.assertTrue(i1 == c);
}
@Test
public void test1_4(){
// 测试通过
int i1 = 128;
double d = 128.0;
Assert.assertTrue(i1 == d);
}
// Integer与int比较,都会进行自动拆装箱,实际是Integer中
// 的value与int进行比较,所以不管大小,只要值相等,这两个变量就相等。
@Test
public void test2_1(){
// 测试通过
int i1 = 10;
Integer i2 = 10;
Assert.assertTrue(i1 == i2);
}
@Test
public void test2_2(){
// 测试通过
int i1 = 128;
Integer i2 = 128;
Assert.assertTrue(i1 == i2);
}
// Integer与Integer比较,如果都是常量赋值的,那么在-128到127范围内的比较,就是常量池对象的比较,如果在范围外,
// 就是堆里边对象的比较。
@Test
public void test3_1(){
// 测试通过
Integer i1 = 10;
Integer i2 = 10;
Assert.assertTrue(i1 == i2);
}
@Test
public void test3_2(){
// 测试不能通过
Integer i1 = 128;
Integer i2 = 128;
Assert.assertTrue(i1 == i2);
}
// Integer与Integer比较,不管大小,如果有一个是new Integer()的方式
// 创建的,那肯定就不相等。
@Test
public void test4_1(){
// 测试不能通过
Integer i1 = 10;
Integer i2 = new Integer(10);
Assert.assertTrue(i1 == i2);
}
@Test
public void test4_2(){
// 测试不能通过
Integer i1 = 128;
Integer i2 = new Integer(128);
Assert.assertTrue(i1 == i2);
}