分析下为什么,public Class Main{ public static void main(String[] args){ Integer i1 = 100; Integer i2 = 100; Integer i3 = 200; Integer i4 = 200; System.out.println(i1 == i2); //true System.out.println(i3 == i4); //false; } }
时间: 2023-05-11 21:02:51 浏览: 68
这是因为Java对于Integer类型的缓存机制,对于-128到127之间的整数,会进行缓存,所以i1和i2的值都在缓存范围内,所以它们的引用地址相同,而i3和i4的值超出了缓存范围,所以它们的引用地址不同。
相关问题
public class Main { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 200; Integer i4 = 200; System.out.println(i1==i2); System.out.println(i3==i4); } }
这段代码输出的结果是:
```
true
false
```
这是因为 Java 在运行时会对 Integer 类型的数值进行缓存,范围在 -128 到 127 之间的数值会被缓存。因此,i1 和 i2 的数值都在缓存范围内,所以它们指向的是同一个对象,比较结果为 true;而 i3 和 i4 的数值超出了缓存范围,所以它们指向的是不同对象,比较结果为 false。如果想要比较 Integer 类型的数值是否相等,应该使用 equals() 方法,而不是使用 == 进行比较。
public class Test { public static void main(String[] args) { int i = 0: Integer j = new Integer(0) ; System.out.println(i==j); System.out.println(j.equals(i));
这段代码存在语法错误,不能编译通过。其中第二行中冒号应该改为分号,变量类型应该为 `Integer` 而非 `int`。修改后的代码如下:
```
public class Test {
public static void main(String[] args) {
int i = 0;
Integer j = new Integer(0);
System.out.println(i == j);
System.out.println(j.equals(i));
}
}
```
这段代码首先定义了一个 `int` 类型的变量 `i`,并将其赋值为 `0`;然后定义了一个 `Integer` 类型的变量 `j`,并将其赋值为 `0` 的包装类型 `new Integer(0)`。接下来分别输出了 `i == j` 和 `j.equals(i)` 的结果。
由于 `i` 和 `j` 数据类型不同,因此在比较相等性时会进行类型转换。在 `i == j` 中,`j` 会被自动拆箱,得到 `0`,然后和 `i` 进行比较,因此结果为 `true`。在 `j.equals(i)` 中,由于 `i` 是一个 `int` 类型的基本数据类型,因此会自动装箱为 `Integer` 类型,然后进行比较,因此结果也为 `true`。