Java中的包装类,以及自动装箱和拆箱
2018-08-01 本文已影响13人
DeeJay_Y
包装类
由于基本类型只能做一些简单的操作和运算,所以Java又封装了各种基本类型,提供了包装类。
包装类提供了更多复杂的方法和变量。
来给出各个基本类型的包装类型
| 基本类型 | 包装类型 |
|---|---|
| byte | Byte |
| short | Short |
| char | Character |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| boolean | Boolean |
以Integer为例说明:
类型转换
String ===> int
int intValue()static int parseInt(String s)
int ===> String
+ ""String toString()static String toString(int i)
自动装箱和拆箱
来看一些自动装箱拆箱的例子
Integer i = 10;这句代码就是自动装箱,相当于Integer i = new Integer(10);
Integer i = 10; int a = i; 这句给a赋值i的语句,就是自动拆箱。相当于int a = i.intValue();
Integer i1 = 10;
Integer i2 = 20;
Integer i3 = i1 + i2;
前2句是自动装箱,第3句是先拆箱求和之后再装箱,相当于Integer i3 = new Integer(i1.intValue() + i2.intValue());
ArrayList li = new ArrayList ();
li.add(1); // 相当于li.add(new Integer(i))