Integer.valueOf()方法 java

来源:互联网 发布:企业网络搭建方案文档 编辑:程序博客网 时间:2024/04/27 22:57

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);         }

Integer.valueOf()方法基于减少对象创建次数和节省内存的考虑,缓存了[-128,127]之间的数字。此数字范围内传参则直接返回缓存中的对象。在此之外,直接new出来。

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);          }      }

测试代码

package com.mooing.hessian;public class ValueOfTest {    public static void main(String[] args) {//      int a=1;//      Integer b=new Integer(1);//      Integer c=Integer.valueOf(1);//      Integer d=new Integer(250);//      Integer e=Integer.valueOf(250);//      //      System.out.println("== 结果:");//      System.out.println(a==b);//      System.out.println(a==c);//      System.out.println(b==c);//      System.out.println(d==e);//      //      System.out.println("equal 结果:");//      System.out.println(b.equals(c));//      System.out.println(d.equals(e));        Integer i1 = Integer.valueOf(12);          Integer i2 = Integer.valueOf(12);          Integer i3 = Integer.valueOf(129);          Integer i4 = Integer.valueOf(129);        System.out.println("== 结果:");        System.out.println(i1==i2);          System.out.println(i3==i4);        System.out.println("equal 结果:");        System.out.println(i1.equals(i2));          System.out.println(i3.equals(i4));      }    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);         }    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);          }      }}

结果
true
false
true
true

原创粉丝点击