提高你的Java代码质量吧:优先使用整形池

来源:互联网 发布:搜索引擎seo基本理念 编辑:程序博客网 时间:2024/04/30 18:37

一、分析 

包装类型产生对象的两种方式 

1.new产生的Integer对象 

new声明的就是要生成一个对象,没二话,这就是两个对象,地址肯定不相等 

2.装箱生成的对象 

装箱动作是通过valueOf()方法实现的,我们阅读以下Integer.valueOf的实现代码 

public static Integer valueOf(int i){     final int offset = 128;     if(i >= -128 && i <= 127){         return IntegerCache.cache(i + offset);     }     retrun new Integer(i); } 

这段代码,如果是-128至127之间的int类型转换为Integer对象,则直接从cache数组中获得,代码如下: 

static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static{     for(int i = 0; i < cache.length; i++){         cache[i] = new Integer(i-128);     } } 

cache是IntegerCache内部类的一个静态数组,容纳的是-128到127之间的Integer对象,通过valueOf产生包装对象时,如果int参数在-128和127之间,则直接从整形池中获得对象,不在该范围的int类型则通过new生成包装对象。  

二、场景 

代码如下 

public static void main(String[] args){     Scanner input = new Scanner(System.in);     while(input.hasNextInt()){         int ii = input.nextInt();         System.out.println("\n===" + ii + "的相等判断 ===");         //通过两个new产生的Integer对象         Integer i = new Integer(ii);         Integer j = new Integer(ii);         System.out.println("new 产生的对象:" + (i == j));          //基本类型转换为包装类型后比较         i = ii;         j = ii;         System.out.println("基本类型转换的对象:" + (i == j));          //通过静态方法生成的一个实例         i= Integer.valueOf(ii);         j = Integer.valueOf(ii);         System.out.println("valueOf产生的对象:" + (i == j));     } } 

分别输入127、128、55,结果如下: 

===127的相等判断=== 

new产生的对象:false 

基本类型转换的对象:true 

valueOf产生的对象:true 

 

===128的相等判断=== 

new产生的对象:false 

基本类型转换的对象:false 

valueOf产生的对象:false 

 

===555的相等判断=== 

new产生的对象:false 

基本类型转换的对象:false 

valueOf产生的对象:false 


通过上面的分析,127是直接从整型池中获得的,不管你输入多少次127数字,获得的都是同一个对象。而128、555超出了整型范围,是通过new产生的新对象。 

三、建议 

声明包装类型的时候,使用valueOf()生成,而不是通过构造函数生成。这样使用整型池,不仅仅提高了系统性能,同时节约了内存空间 

原创粉丝点击