跟着刚哥梳理java知识点——包装类(十)

Java为8种基本数据类型都提供了对应的包装器类型

装箱和拆箱:

public class Main {
  public static void main(String[] args) {
    Integer i = 10;//装箱
    int n = i;//拆箱
  }
}

装箱:基本数据类型转换成包装类。

  实现:通过调用包装类的valueOf方法实现的

拆箱:包装类转换成基本数据类型。

  实现:通过调用包装器的 xxxValue方法实现的(xxx代表对应的基本数据类型)

1)基本类型中的整数型:

public class Main {
  public static void main(String[] args) {
    Integer i1 = 100;
    Integer i2 = 100;
    Integer i3 = 200;
    Integer i4 = 200;
    System.out.println(i1==i2);
    System.out.println(i3==i4);
  }
}

输出结果:true  false

看看valueOf源码就知道了

public static Integer valueOf(int i) {
  if(i >= -128 && i <= IntegerCache.high)
    return IntegerCache.cache[i + 128];
  else
    return new Integer(i);
}

而其中IntegerCache类的实现为:

private static class IntegerCache {
  static final int high;
  static final Integer cache[];
  static {
    final int low = -128;
    // high value may be configured by property
    int h = 127;
    if (integerCacheHighPropValue != null) {
      // Use Long.decode here to avoid invoking methods that
      // require Integer's autoboxing cache to be initialized
      int i = Long.decode(integerCacheHighPropValue).intValue();
      i = Math.max(i, 127);
      // Maximum array size is Integer.MAX_VALUE
      h = Math.min(i, Integer.MAX_VALUE - -low);
    }
  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() {}
}

从源码中可以看出,在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象

2)基本类型中的浮点型:

public class Main {
  public static void main(String[] args) {
    Double i1 = 100.0;
    Double i2 = 100.0;
    Double i3 = 200.0;
    Double i4 = 200.0;
    System.out.println(i1==i2);
    System.out.println(i3==i4);
  }
}

输出结果:false false

通过查看源码就马上知道答案了。

public static Double valueOf(String s) throws NumberFormatException {
  return new Double(parseDouble(s));
}

原来valuOf将所有的值都重新new了一个对象。

3)基本类型中的布尔型:

public class Main {
  public static void main(String[] args) {
    Boolean i1 = false;
    Boolean i2 = false;
    Boolean i3 = true;
    Boolean i4 = true;
    System.out.println(i1==i2);
    System.out.println(i3==i4);
  }
}

输出结果:true true

同样的看一下valueOf源码:

public static Boolean valueOf(boolean b) {
  return (b ? TRUE : FALSE);
}

而其中的 TRUE 和FALSE又是什么呢?在Boolean中定义了2个静态成员属性:

public static final Boolean TRUE = new Boolean(true);
/** 
* The <code>Boolean</code> object corresponding to the primitive 
* value <code>false</code>. 
*/
public static final Boolean FALSE = new Boolean(false);

至此,大家应该明白了为何上面输出的结果都是true了。

对于布尔的包装类想多说一句,看以下代码:

Boolean b = new Boolean("123");
System.out.println(b);

执行结果:false。

并不会运行错误。

 

总结:

Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是都是相似的(整数型都是-128 - 127 之间cache,Character是<=127的cache)。

Double、Float的valueOf方法的实现是一样的(都是重新 new)。

Bolean 的valueOf方法 只看值是否为true和false。

 

 

posted @ 2017-03-23 07:21  啤酒大泡泡  阅读(217)  评论(0编辑  收藏  举报