Java后台开发面试
来源:互联网 发布:头脑风暴软件 编辑:程序博客网 时间:2024/05/16 08:36
面试题:int和Integer的区别?什么时候用int,什么时候用Integer?
解析
Java提供了两种不同的类型:引用类型和基本类型。为实现基本数据类型到面向对象的转化,Java为每个基本数据类型提供了对应的包装类(或者叫作封装类),如下表所示:表-基本数据类型对应的包装类
引用类型和基本类型的行为完全不同,并且它们具有不同的语义、特征和用法。另外,对象引用实例变量的默认值为null,而基本类型实例变量的默认值与它们的类型有关。
int和Integer的区别:
int是java的基本数据类型,Integer是Java为int提供的封装类。
int是基本数据类型,Integer是引用类型。当要装入ArrayList、HashMap等容器时,需要作为对象来装入,此时选择Integer。因为容器都是装object的。
int 初始化
int i =1;
int默认值是0
Integer 初始化
Integer i= new Integer(1);
Integer 默认值是null
根据int和Integer默认值不同,确定不同的使用场景。比如,可以用Integer来表示没有参加考试,用int表示考试成绩为0。
下面还想强调一点:
Integer ina = 2;Integer inb = 2;System.out.println("两个2自动装箱后是否相等:" + (ina == inb)); // 输出trueInteger biga = 128;Integer bigb = 128;System.out.println("两个128自动装箱后是否相等:" + (biga == bigb));// 输出false
同样是两个int类型的数值自动装箱成Integer实例后,如果是两个2自动装箱后就相等;但如果是两个128自动装箱后就不相同,为什么呢?从源码中找答案。
查看 Java系统中java.lang.Integer类的源代码
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the -XX:AutoBoxCacheMax=<size> option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} }
IntegerCache类是Integer类中一个私有的静态类。IntegerCache类是用来实现缓存支持的,并支持-128到127之间的自动装箱过程。这个缓存会在Integer类第一次被使用时被初始化。以后,在创建新的Integer对象之前,会先在IntegerCache.cache中查找。
因此,-128到127之间的同一个整数自动装箱成Integer实例时,永远都是引用cache数组的同一个数组元素,所以它们全部相等;但每次把一个不在-128到127范围内的整数自动装箱成Integer实例时,系统总是会重新创建一个Integer实例,所以两个128自动装箱成Integer实例后就不相等。
- Java后台开发面试
- Java后台开发面试
- 互联网公司Java后台开发面试经历
- 互联网公司Java后台开发面试
- Java后台开发面试知识点总结
- QNR(JAVA后台开发)面试题目
- 后台开发面试
- 腾讯后台开发面试
- 后台开发面试
- 后台开发面试经验
- 后台开发面试经验
- 腾讯后台开发面试
- java后台面试大全
- 网络后台开发面试题目
- 腾讯后台开发面试总结
- 腾讯后台开发面试经验
- BAT后台开发面试题库
- 后台开发面试问题整理
- 安步 数据库操作
- 生活琐事
- 如何区分python入门教程?
- SecKey API returned:-25293 :unknown error -1=ffffffffffffffff解决办法
- POJ3311:Hie with the Pie(floyd+状态压缩DP)
- Java后台开发面试
- 从一个jsp页面跳转到另一个jsp页面时的参数传递
- ASCII对照表
- SDUT 3893 (山东省第八届ACM省赛A题) Return of the Nim 博弈nim+威佐夫
- volatile
- 算法系列——Candy
- Linux-进程、进程组、作业、会话、控制终端详解
- HDU 3499 Flight(SPFA+map)
- 51nod--1092 回文字符串(非连续!)