int和Integer的区别
来源:互联网 发布:西西影音软件下载 编辑:程序博客网 时间:2024/06/05 03:16
Java面试题——int 和Integer的区别
答:int是基本数据类型之一,Integer是int的包装类。
面试官:......然后呢?
答:......
怎么能忘了,在梳理一下。
理解int和Integer的区别,首先需要了解两个概念:
1.Java的常量池
2.Java的自动拆箱和装箱
好了,翠花,上酸菜。
Demo:
int i = 127; Integer i2 = 127; //自动装箱,Integer i2=Integer.valueOf(127); Integer i3 = new Integer(127); System.out.println(i == i2); //ture ,在进行比较时,i2会自动拆箱为int System.out.println(i == i3); //ture ,在进行比较时,i3会自动拆箱为int System.out.println(i2 == i3); //false ,两个对象比较,一个存在于常量池,一个存在于堆中。 int n = 128; Integer n2 = 128; Integer n3 = new Integer(128); System.out.println(n == n2); //ture ,同上 System.out.println(n == n3); //ture System.out.println(n2 == n3); //false Integer o = 127; Integer m = 128; System.out.println(i2 == o); //ture ,127存在于常量池中,是同一个值 System.out.println(n2 == m); //false ,128不存在常量池中,n2和m代表不同的对象,其值分别存储在堆中不同位置。
其中,Integer. valueOf的源码如下:
/** * Returns a {@code Integer} instance for the specified integer value. * <p> * If it is not necessary to get a new {@code Integer} instance, it is * recommended to use this method instead of the constructor, since it * maintains a cache of instances which may result in better performance. * * @param i * the integer value to store in the instance. * @return a {@code Integer} instance containing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128]; } /** * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing */ private static final Integer[] SMALL_VALUES = new Integer[256]; static { for (int i = -128; i < 128; i++) { SMALL_VALUES[i + 128] = new Integer(i); } }
结论:
1.new出来的Integer相比较,均为false,代表两个不同的对象,存储在堆中的位置不一样。
2.非new出来的Integer相比较,如果数在-128到127之间,则是true,否则为false 。
3.int和Integer相比较,均为ture,因为Integer会先自动拆箱为int,再进行比较。
4.Integer和new Integer相比较,均为false。
如果值在-128到127之间,Integer的值存在于常量池,new Integer的值存在于堆中;
如果没在-128到127之间,那么均视为new Integer,同结论1。
1 0
- int 和 Integer 的区别
- int 和 Integer 的区别
- int和Integer的区别
- int和Integer的区别
- int 和 integer的区别
- Integer和int的区别
- Integer 和 int 的区别
- int和integer的区别
- int和Integer的区别
- int 和integer的区别
- int 和 Integer的区别
- int 和integer的区别
- int 和integer的区别
- Integer和Int的区别
- int 和integer的区别
- int 和integer的区别
- Int 和integer的区别
- int 和Integer的区别
- 开发切记:欲速则不达
- centos之lnmp
- Leetcode题集——rotate image
- 使用Jsoup 抓取页面的数据
- inotify+rsync安装配置
- int和Integer的区别
- Android 热修复三部曲之基本的Ant打包脚本
- OPENCV入门教程五:flip垂直水平镜像
- (2)从零开始的操作系统开发日记
- 10010---centos关机与重启命令详解
- wait和waitpid函数总结
- SCAU_专题训练2&3
- 嵌入式开发15天(标准IO,交叉编译,模块化编程)
- 男生和女生的区别