Integer是int

1、Integer是int的包装类,int则是java的一种基本数据类型 
2、直接给Integer变量赋值,实际是对象的引用,相当于实例化了对象生成一个指针指向此对象,而int则是直接存储数据值 
3、Integer的默认值是null,int的默认值是0

术语一点讲:Integer a = 200; 是一个装箱的过程,相当于integer a = new(任意整形); a = 200;

在if (a == b)的时候,进行了拆箱的操作,将Integer  a拆箱为int a,b同理,然后进行值比较

注意:如果是new出来的a,则它的取值范围是-127~128,超出范围进行对比,则两个看似相等其实不等

Integer a = 200;
Integer b = 200;
if (a==b)
{ System.out.println("a==b"); }
else 
{ System.out.println("a!=b"); }

这里面涉及到2个知识点:

1、Integer a = 200; 

     Integer b = 200; 

     //直接值比较

     --------------------------------------------------------

     integer a = new(100); 

     integer b = new(100);    

  //结果 a!=b,new出来的比的是地址

     a = 30;

     b = 30;

     //结果 a==b,如果ab取值不在-127~128范围内,则不相同

     --------------------------------------------------------

     integer a = integer.valueOf(200);

     integer b = integer.valueOf(200);

     //结果 a==b,如果ab取值不在-127~128范围内,则取表地址,否则取值(暂时这么理解,实则应该不是这样)

1    public static Integer valueOf(int i) {
2        if (i >= IntegerCache.low && i <= IntegerCache.high)
3            return IntegerCache.cache[i + (-IntegerCache.low)];
4        return new Integer(i);
5    }

 

 1    private static class IntegerCache {
 2         static final int low = -128;
 3         static final int high;
 4         static final Integer cache[];
 5  
 6         static {
 7             // high value may be configured by property
 8             int h = 127;
 9             String integerCacheHighPropValue =
10                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
11             if (integerCacheHighPropValue != null) {
12                 try {
13                     int i = parseInt(integerCacheHighPropValue);
14                     i = Math.max(i, 127);
15                     // Maximum array size is Integer.MAX_VALUE
16                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
17                 } catch( NumberFormatException nfe) {
18                     // If the property cannot be parsed into an int, ignore it.
19                 }
20             }
21             high = h;
22  
23             cache = new Integer[(high - low) + 1];
24             int j = low;
25             for(int k = 0; k < cache.length; k++)
26                 cache[k] = new Integer(j++);
27  
28             // range [-128, 127] must be interned (JLS7 5.1.7)
29             assert IntegerCache.high >= 127;
30         }
31  
32         private IntegerCache() {}
33     }

 

posted @ 2018-04-03 10:36  一字节  阅读(510)  评论(0编辑  收藏  举报