Java 包装类(Wrapper Class)是将基本数据类型转换为对象的方式,每个基本数据类型在 java.lang 包中都有一个相应的包装类:
-
Boolean
对应基本类型boolean
-
Character
对应基本类型char
-
Integer
对应基本类型int
-
Float
对应基本类型float
-
Double
对应基本类型double
-
Byte
对应基本类型byte
-
Short
对应基本类型short
-
Long
对应基本类型long
包装类 自动拆箱 自动装箱
java"> public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(Integer.valueOf(10));
list.add(20);//自动装箱
list.add(30);
Integer firstElement= list.get(0);
int firstPrimitive=list.get(0);//自动拆箱
System.out.println("First element as an Integer: " + firstElement);
System.out.println("First element as an int: "+ firstPrimitive);
for (Integer integer : list) {
System.out.println(integer);
}
}
返回
java">First element as an Integer: 10
First element as an int: 10
10
20
30
包装类缓存
java"> public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=100;
Integer b=100;
System.out.println("a == b is "+ (a == b));//true 在缓存范围内 -128 -127
System.out.println("a.equals(b) is "+ a.equals(b));//
Integer c=200;
Integer d=200;
System.out.println("c == d is "+ (c == d));//false
System.out.println("c.euals(d) is "+ c.equals(d));//
}
返回
java">a == b is true
a.equals(b) is true
c == d is false
c.euals(d) is true