Interge i3 = 200;Integer i4 = 200;
时间: 2023-08-10 15:02:48 浏览: 45
在Java中,对于基本类型的包装类,如Integer、Boolean、Double等,如果它们的值相等,它们所对应的对象也是相等的,即使用"=="比较时返回true。但是,如果超过了它们的缓存范围,就不再相等了。
在这个例子中,因为Integer类型有一个缓存范围,默认情况下会缓存-128到127之间的整数,所以当i3和i4赋值为200时,它们所对应的内存地址不相同,使用"=="比较时返回false。而如果i3和i4赋值为-128到127之间的整数时,它们所对应的对象是相等的,使用"=="比较时返回true。因此,正确的比较方式是使用equals方法,即i3.equals(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); //true System.out.println(i3 == i4); //false; } }
这是因为Java对于Integer类型的缓存机制,对于-128到127之间的整数,会进行缓存,所以i1和i2的值都在缓存范围内,所以它们的引用地址相同,而i3和i4的值超出了缓存范围,所以它们的引用地址不同。
Integer i3 = Integer.valueOf(5); Integer i4 = Integer.valueOf(5); System.out.println(i3==i4);
The output of this code will be "true".
Explanation:
When we use the Integer.valueOf() method to create Integer objects with values between -128 and 127, the JVM caches these objects and returns the same object for subsequent calls to the method with the same argument.
In this case, both i3 and i4 have the value 5, which falls within the cached range. Therefore, both Integer objects are the same object in memory, and the comparison using the == operator will return true.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)