在Java中每个基本数据类型都有对应的一个类,
基本类型 | 对应的类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
void | Void |
boolean | Boolean |
- 这些对象包装器是不可变的,也就是说一旦生成了一个对应的对象之后里面的值就不能改变了。 并且它们还是final的,所以不能定义它们的子类。
- 当我们在构造列表`(例如ArraList<Integer>)`的时候,`<>`之间只能传递对象,这个时候我们就可以传递它们对应的类。
一、装箱
- 既然这些类都是箱子,那么把基本类型变成这些类的对象就是 装箱 的操作了。但是装箱的操作是由编译器自动来完成的,跟jvm无关。所以又称为自动装箱。
Integer a=10;//相当于是Integer a = Integer.valueOf(10);
二、拆箱
当我们将Integer对象赋给int时,将会自动拆箱。也就是编译器会完成以下动作:
int b=a; => int b = a.intValue();
有时的计算可以自动拆箱和装箱,例如:
a++;
三、注意事项
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
从以上说明可以看到不是任何时候调用 valueOf(int i)
都会新实例化一个对象返回
Integer a = 90;
Integer b = 90;
Integer c = Integer.valueOf(90);
Integer d = new Integer(90);
if (a == b) {
System.out.println("a==b");
}
if (c == b) {
System.out.println("c==b");
}
if (c == d) {
System.out.print("c==d");
}else{
out.println("c!=d");
}
----------
输出:
a==b
c==b
c!=d。
实际上,当初始化的值 在[-128,127]这个区间的时候只会返回已经缓存的对象,所以这个时候都是一样的,只有当初始的值不在这个范围的时候才会返回一个新new的对象,这个时候他们就不一样了
Integer b = -129;
if (a == b) {
System.out.println("a==b");
}else{
System.out.println("a!=b");
}
输出:
a!=b
四、比较
当对象包装器直接比较的时候是跟上面的所说的一样,但是当对象包装器和一般的基本类型比较的时候就是先拆箱然后比较两者直接的“内容(这里就是数值)”,所以当一个对象包装器和一时候,如果两者的值一样那么它们就是一样的
Integer d = new Integer(90);
int e = 90;
if (e == d) {
out.println("e==d");
}
输出:
("e==d");