Integer 是 int 的包装类,包装了一个基本类型 int 的值。该类提供常用得多种方法,值得我们去探究一下。
定义
Integer 类的定义语句如下:
public final class Integer extends Number implements Comparable<Integer>
从这里我们可以了解到以下几点:
- 被 final 关键字修饰过,所以该类不可以被继承。
- 该类继承了 Number 父类(可以看 Number 类解读),所以 Integer 类重写了对应方法,可以调用longValue、floatValue、doubleValue等系列方法返回对应的类型的值。
属性
私有属性
private final int value;
@Native private static final long serialVersionUID = 1360826667806852920L;
value 属性就是 Integer 类里面保存的 int 值。当我们创建 Integer 对象的时候该会把传进来的 int 值赋给该属性。因为该属性是 final 类型。也就说明,一旦一个 Integer 对象被初始化之后,就无法再改变 value 的值。如果需要改变需要调用 valueOf 方法。
这里穿插说一个样例,应该经常会看到这样的执行语句:
Integer a = new Integer(5);
a = 7;
运行都会知道这个时候输出 a 的值,它的值是 7。但是前面又说 value 的值是 final 属性的,不可以改变。这里其实就是虚拟机做的一些处理,它实际会执行 valueOf 方法修改 value 值。
共有属性
// 表示 int 类型能够表示的最小值,值为 -2^31。
public static final int MIN_VALUE = 0x80000000;
// 表示 int 类型能够表示的最大值,值为 2^31 - 1。
public static final int MAX_VALUE = 0x7fffffff;
// 表示基本类型 int 的 Class 实例。
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
// 表示二进制补码形式下 int 值的比特位数。
public static final int SIZE = 32;
// 表示二进制补码形式下 int 值的字节数。1.8以后才有
public static final int BYTES = SIZE / Byte.SIZE;
构造方法
Integer 提供了两个构造方法,一个传了 int 类型,一个是 String类型。
/**
* Constructs a newly allocated {@code Integer} object that
* represents the specified {@code int} value.
*
* @param value the value to be represented by the
* {@code Integer} object.
*/
public Integer(int value) {
this.value = value;
}
/**
* Constructs a newly allocated {@code Integer} object that
* represents the {@code int} value indicated by the
* {@code String} parameter. The string is converted to an
* {@code int} value in exactly the manner used by the
* {@code parseInt} method for radix 10.
*
* @param s the {@code String} to be converted to an
* {@code Integer}.
* @exception NumberFormatException if the {@code String} does not
* contain a parsable integer.
* @see java.lang.Integer#parseInt(java.lang.String, int)
*/
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
也就是说我们调用 Integer a = new Integer(5); 当于是给 Integer 对象里面的私有属性 value 的赋值,而且不论传的参数是哪个类型最后都会转换给 int 类型且是一个十进制的整数。
其他方法
parseInt 函数
从构造函数中我们可以看到传过来是 String 类型的时候是通过该函数转换为 int 类型的。
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
// 第一步、判断字符串参数是否为null
if (s == null) {
throw new NumberFormatException("null");
}
// 第二步,判断基数是否小于最小基数为2
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
// 第三步,判断基数是否大于最大基数为36
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " &