Java - 包装类

59

包装(封装)类:

扩展基本数据类型的功能

包装类是对象, 基本数据类型是常量

基本数据类型包装类
byteByte
shortShort
intInteger
longLong
booleanBoolean
floatFloat
doubleDouble
charCharacter
class test {
    public static void main(String[] args) {

        Integer a = 1000;
        Integer b = Integer.valueOf(1000);
        Integer c = Integer.valueOf(1000).intValue();
        Integer d = Integer.parseInt("1000");
    }
}

/*
对于以上 a != b != c != d
如果值换成小于127的数就是==, 因为有小整形常量池(-128--127)
*/

拆箱和装箱功能:

拆箱:

将包装类的对象转换为基本数据类型

Integer a = 100; --> int b = a;

装箱:

将基本数据类型包装为包装类

int a = 100; --> Integer b = a;

int a = 10;

Integer b = integer.valueOf(a) // valueOf参数包装成Integer对象返回

自动拆装箱:

目前Java中提供了自动拆装箱功能

如上所示的将 int 附给 Integer 就是自动装箱, 将Integer附给int就是自动拆箱

class Test {
    public static void main(String[] args) {
        int a = 100;
        Integer b = a; // 自动装箱
        Integer c = 100; // 自动装箱
        int d = c; // 自动拆箱
    }
}

Void包装类:

Void是对void的引用, 不能被实例化. 如果方法返回值是Void, 那么该方法就只能返回null

用途:

  • 让Callable的call方法只支持抛异常
public class Test {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        try {
            // 在Callable接口的call方法中必须有一个返回值, 但我们想让线程只支持抛出异常
            Future<Void> future = pool.submit(() -> {
                Thread.sleep(3000);
                return null;
            });
        } catch (Exception ignored) {
        } finally {
            pool.shutdown();
            pool.close();
        }
    }
}
  • 使用泛型函数不需要返回值时