八个基本数据类型:

  • boolean 1字节
  • byte 8bit =1字节
  • char 2字节
  • short 2字节
  • int 4字节
  • float 4字节
  • long 8字节
  • double 8字节

包装类:

  • Character
  • Short
  • Integer
  • Byte
  • Float
  • Double
  • Boolean

缓存池:

  • new Integer(1234) 每次会创建一个新的对象
  • Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。

valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。

著作权归https://pdai.tech所有。
链接:https://www.pdai.tech/md/java/basic/java-basic-lan-basic.html

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

在 Java 8 中,Integer 缓存池的大小默认为 -128~127。

编译器会在缓冲池范围内的基本类型自动装箱过程调用 valueOf() 方法,因此多个 Integer 实例使用自动装箱来创建并且值相同,那么就会引用相同的对象。

Integer a = 1234;
Integer b = 1234;
System.out.println(m == n);    // true

基本类型对应的缓冲池如下:

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

在使用这些基本类型对应的包装类型时,就可以直接使用缓冲池中的对象。

如果在缓冲池之外:

Integer a = 1234;
Integer b = 1234;
System.out.println(m == n);  // false

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注