您的位置:首页 > 产品设计 > UI/UE

new Integer(1)和Integer.valueOf(1)的区别

2016-06-21 11:18 423 查看
java.lang包中的Integer类是我们比较常用的类,比如以下代码:

Integer a=new Integer(1)

Integer a=Integer.valueOf(1);

两个都是得到一个Integer对象,但是Integer.valueOf的效率高。为什么呢?因为Integer.valueOf用到了缓存机制。

其中Integer.valueOf方法代码如下:

public static Integer valueOf(int i) {

final int offset = 128;

if (i >= -128 && i <= 127) { // must cache 

   return IntegerCache.cache[i + offset];

}

        return new Integer(i);

 }

在这个类中使用到了一个辅助类IntegerCache,其中IntegerCache的源代码如下:

private static class IntegerCache {

private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {

   for(int i = 0; i < cache.length; i++)

cache[i] = new Integer(i - 128);

}

    }

可以看到在IntegerCache中已经初始化了cache数组。所以,要注意的是,new Integer返回的永远是不同的对象,但是当整数范围在-128<i<=127时,Integer.valueOf返回的是同一个对象。

看下面代码:

Integer a=new Integer(1);   

        Integer b=new Integer(1);   

          

        //整数范围在-128到127之间,返回的是同一个对象   

        Integer c=Integer.valueOf(1);   

        Integer d=Integer.valueOf(1);   

          

        //返回的不是同一个对象   

        Integer e=Integer.valueOf(200);   

        Integer f=Integer.valueOf(200);   

          

        System.out.println(a==b);   

        System.out.println(c==d);   

        System.out.println(e==f);

 

程序运行的结果为:

false

true

false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息