Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,495,102字

该文章投稿至Nemo社区   Java  板块 复制链接


java中Integer值比较笔记

发布于 2017/08/31 19:16 4,647浏览 0回复 1,090

先贴一段代码:

public static void main(String[] args) {
Integer a1 = Integer.valueOf(60);
Integer b1 = 60;
System.out.println("1:= "+(a1 == b1));


Integer a2 = 60;
Integer b2 = 60;
System.out.println("2:= "+(a2 == b2));


Integer a3 = new Integer(60);
Integer b3 = 60;
System.out.println("3:= "+(a3 == b3));

Integer a4 = 129;
Integer b4 = 129;
System.out.println("4:= "+(a4 == b4));

System.err.println("a1:eq "+a1.equals(a1));
System.err.println("a2:eq "+a2.equals(b2));
System.err.println("a3:eq "+a3.equals(b3));
System.err.println("a4:eq "+a4.equals(b4));
System.err.println("a4:eq "+a4.equals(b4));
}e

猜想的结果是:

1:= true
2:= true
3:= true
4:= true
a1:eq true
a2:eq true
a3:eq true
a4:eq true
a4:eq true

然而实际执行结果:

1:= true
2:= true
3:= false
4:= false
a1:eq true
a2:eq true
a3:eq true
a4:eq true
a4:eq true

显然猜想错误。

要知道为啥会出现这种情况,就涉及到Java缓冲区和堆的问题。

java中Integer类型对于-128-127之间的数是缓冲区取的,所以用等号比较是一致的。但对于不在这区间的数字是在堆中new出来的。所以地址空间不一样,也就不相等。

Integer b3=60,这是一个装箱过程也就是Integer b3=Integer.valueOf(60)

所以,如果碰到Integer比较值是否相等需要用intValue(),或者使用equals比较。

点赞(0)

上一个文章:Ajax文件上传

下一个文章:【转载】vim常用命令总结

点了个评