苏州网站建设推荐好先生科技,有了空间怎么做网站,漯河市住房和城乡建设局网站,在线图片编辑尺寸大小昨天例行code review时大家有讨论到int和Integer的比较和使用。 这里做个整理#xff0c;发表一下个人的看法。【int和Integer的区别】int是java提供的8种原始类型之一#xff0c;java为每个原始类型提供了封装类#xff0c;Integer是int的封装类。int默认值是0#xff0c;…昨天例行code review时大家有讨论到int和Integer的比较和使用。 这里做个整理发表一下个人的看法。 【int和Integer的区别】 int是java提供的8种原始类型之一java为每个原始类型提供了封装类Integer是int的封装类。int默认值是0而Integer默认值是nullint和Integer无论是否new比较都为true 因为会把Integer自动拆箱为int再去比Integer是引用类型用比较两个对象其实比较的是它们的内存地址所以不同的Integer对象肯定是不同的但是对于Integer i*java在编译时会将其解释成Integer iInteger.valueOf(*)。但是Integer类缓存了[-128,127]之间的整数 所以对于Integer i1127与Integer i2127 来说i1i2因为这二个对象指向同一个内存单元。 而Integer i1128与Integer i2128 来说i1i2为false。【各自的应用场景】 Integer默认值是null可以区分未赋值和值为0的情况。比如未参加考试的学生和考试成绩为0的学生加减乘除和比较运算较多用int容器里推荐用Integer。 对于PO实体类如果db里int型字段允许null则属性应定义为Integer。 当然如果系统限定db里int字段不允许null值则也可考虑将属性定义为int。对于应用程序里定义的枚举类型 其值如果是整形则最好定义为int方便与相关的其他int值或Integer值的比较Integer提供了一系列数据的成员和操作如Integer.MAX_VALUEInteger.valueOf(),Integer.compare(),compareTo(),不过一般用的比较少。建议一般用int类型这样一方面省去了拆装箱另一方面也会规避数据比较时可能带来的bug。【附Integer类的内部类IntegerCache和valueOf方法代码】 public final class Integer extends Number implements ComparableInteger {//。。。。。。。。。。。。private static class IntegerCache {static final int low -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint 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_VALUEh 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() {}}public static Integer valueOf(int i) {assert IntegerCache.high 127;if (i IntegerCache.low i IntegerCache.high)return IntegerCache.cache[i (-IntegerCache.low)];return new Integer(i);}//。。。。。。。。。。。。。}refjava中申明变量用 int 还是 Integer http://bbs.csdn.net/topics/360102986 refInteger与int的种种比较https://www.cnblogs.com/liuling/archive/2013/05/05/intAndInteger.html转载于:https://www.cnblogs.com/buguge/p/8028502.html