java中两个Integer类型的值相比较的问题

转载自: https://www.cnblogs.com/xh0102/p/5280032.html

个Integer类型整数进行比较时,一定要先用intValue()方法将其转换为int数之后再进行比较,因为直接使用==比较两个Integer会出现问题。

总结: 当给Integer直接赋值时,如果在-128到127之间相等的话,它们会共用一块内存,所以此时用==比较不会出现问题。而超过这个范围,则对应的Integer对象有多少个就开辟多少个堆内存,所以此时再使用==进行比较的话就会出错

请看如下程序:

 1 package intAndInteger;
 2 
 3 public class test {
 4     public static void main(String[] args) {
 5         // 两个new出来的Integer类型的数据比较,
 6         //相当于把new出来的地址作比较
 7         
 8         Integer a0 = new Integer(1);// 普通的堆中对象
 9         Integer b0 = new Integer(1);
10         System.out.println("new出来的 " + "a0==b0 :" + (a0 == b0));
11         System.out.println(a0);
12 
13         // 调用intValue方法得到其int值
14         System.out.println("调用intValue " + "a0.intValue() == b0.intValue()" + 
15         (a0.intValue() == b0.intValue()));
16 
17         // 把Integer类型的变量拆箱成int类型
18         int c = 1;
19         System.out.println("将Integer自动拆箱 " + "a0==c: " + (a0 == c));
20 
21         // 其实也是内存地址的比较
22         Integer a1 = 30; // 自动装箱,如果在-128到127之间,则值存在常量池中
23         Integer b1 = 30;
24         System.out.println("直接赋值的两个Integer的比较" + 
25         "a2 == b2: "+ (a1 == b1));
26 
27         Integer a2 = 30;
28         Integer b2 = 40;
29         System.out.println("直接赋值的两个Integer的比较 " + 
30         "a6==b6: " + (a2 == b2));
31 
32         Integer a3 = 128;
33         Integer b3 = 128;
34         System.out.println("直接赋值的两个Integer的比较 " + 
35         "a5 == b5: " + (a3 == b3));
36 
37         Integer a4 = 412;
38         Integer b4 = 412;
39         System.out.println("直接赋值的两个Integer的比较 " + 
40         "a4 == b4: " + (a4 == b4));
41         // 从这里看出,当给Integer直接赋值时,
42         //如果在-128到127之间相等的话,它们会共用一块内存
43         // 而超过这个范围,则对应的Integer对象有多少个就开辟多少个
44 
45         System.out.println("调用intValue " + "a4.intValue() == b4.intValue(): " 
46         + (a4.intValue() == b4.intValue()));
47     }
48 }

运行结果为:

new出来的 a0==b0 :false
1
调用intValue a0.intValue() == b0.intValue()true
将Integer自动拆箱 a0==c: true
直接赋值的两个Integer的比较a2 == b2: true
直接赋值的两个Integer的比较 a6==b6: false
直接赋值的两个Integer的比较 a5 == b5: false
直接赋值的两个Integer的比较 a4 == b4: false
调用intValue a4.intValue() == b4.intValue(): true

综上:在用两个Integer对象比较数值的话,如果是整型值的话最好调用intValue方法来得到一个int类型的值,当然也可将其转变为

float(floatValue),double(longValue)类型来比较。

在JDK API 1.6.0中文版中是这样介绍intValue的,

intValue

public int intValue()
以 int 类型返回该 Integer 的值。
原文地址:https://www.cnblogs.com/FengZeng666/p/10443243.html