我是靠谱客的博主 贤惠裙子,这篇文章主要介绍Java中Integer的详解,现在分享给大家,希望可以做个参考。

在Java中有int和integer两种类型,简单的说Integer是int的引用类型,但是这个引用的类型比较特殊,下面看几个demo:

复制代码
1
2
3
4
5
6
7
Integer a1 = 140; Integer a2 = 140; System.out.println(a1 == a2); Integer b1 = 120; Integer b2 = 120; System.out.println(b1 == b2);

运行结果是:

复制代码
1
2
3
false true

原因: Java对于-128到127之间的数,会进行缓存,Integer i = 127时,会将127进行缓存,下次再写Integer j = 127时,就会直节从缓存中拿取,不会再从新创建对象

所以120的时候地址是一样的,运行是true,大于127的时候重新开辟吗新的地址空间,地址不一致,为false

当然我们也可以强制重新开辟一个新的变量:

复制代码
1
2
3
4
5
6
7
8
9
Integer c1 = new Integer(120); Integer c2 = new Integer(120); System.out.println(c1 == c2); Integer d1 = new Integer(120); Integer d2 = 120; System.out.println(d1 == d2);

运行结果是:

复制代码
1
2
3
false false

这样就更好的验证了我们上面的想法。

如果用Integer和int的值相比,会怎么样呢?

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
Integer e1 = new Integer(120); int e2 = 120; System.out.println(e1 == e2); Integer f1 = new Integer(140); int f2 = 140; System.out.println(f1 == f2); Integer g1 = 120; int g2 = 120; System.out.println(g1 == g2);

运行结果是:

复制代码
1
2
3
4
true true true

原因: 当Integer和int对比的时候,Integer会自动拆箱成为int进行对比

从上面的结论我们得出:

  1. Integer在小于-128到127可以看似是值类型,超过这个范围后,会变成引用类型

  2. Integer与int对比的时候会自动拆箱成int,再进行对比

综合上面,我开始有个一个疑问:

复制代码
1
2
3
4
5
6
7
Integer i1 = 140; Integer i2 = i1; i1++; System.out.println(i2); System.out.println(i2 == i1);

运行结果是:

复制代码
1
2
3
140 false

为什么i2没有随之i1的值改变而改变?

原因: Integer在进行运算的时候回自动调用内部函数intValue().

上面的代码可以拆解成:

复制代码
1
2
3
4
5
6
7
Integer i1 = 140; Integer i2 = i1; i1=Integer.valueOf(i1.intValue()+1); System.out.println(i2); System.out.println(i2 == i1);

根据上面的所有情况,我们可以写一个终极的值类型和引用类型的转换:

复制代码
1
2
3
4
5
6
7
8
Integer i1 = 120; Integer i2 = i1; Integer i3=i1+1; Integer i4=i3-1; System.out.println(i2); System.out.println(i2 == i4);

运行结果:

复制代码
1
2
3
120 true

而当i1=140的时候,i2 == i4就会变成false。

(本文完)

作者:付威

博客地址:http://blog.laofu.online

如果觉得对您有帮助,可以下方的RSS订阅,谢谢合作

如有任何知识产权、版权问题或理论错误,还请指正。

本文是付威的网络博客原创,自由转载-非商用-非衍生-保持署名,请遵循:创意共享3.0许可证

交流请加群113249828: 点击加群 &nbsp 或发我邮件 laofu_online@163.com 

获得最新的博主文章,请关注上方公众号

 


 

最后

以上就是贤惠裙子最近收集整理的关于Java中Integer的详解的全部内容,更多相关Java中Integer内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部