包装类
基本数据类型有着各自的包装类,具体见下表:
基本数据类型 | 包装类 | 基本数据类型 | 包装类 |
---|---|---|---|
byte | Byte | float | Float |
short | Short | double | Double |
int | Integer | char | Character |
long | Long | boolean | Boolean |
基本数据类型为什么要有对应的包装类?原因:
- 比如集合只能存储引用数据类型的数据,可以通过包装类型表示
- 包装类提供了很多方法,可以灵活才做数据
- 表示数据默认值的问题|对接数据库中的某些字段值,null与0的概念不同
自动装箱:基本数据类型–>引用数据类型
自动拆箱:引用数据类型–>基本数据类型
public class DataDemo01 {
public static void main(String[] args) {
int i= 1;
Integer in1 = i; //Integer.valueOf(i);
System.out.println(i);
System.out.println(in1);
int i2 = in1; // in1.intValue()
//test(1.0,2.0); //自动装箱
Integer in = new Integer("123");
System.out.println(in.intValue());
Integer in2 = Integer.valueOf("321");
System.out.println(in2);
}
static void test(Double d1,Double d2){
System.out.println(d1+d2); //自动拆箱
}
}
注:
- Integer(是否new)与int比较,只要数据值相等就相等,因为会先做自动拆箱,然后再比较
- 两个int基本数据类型只要值相等肯定相等,因为值比较数据值
- 两个new比较,无论值是否相等都不相等,new在堆中究开辟空间,地址不同
- 如果一个Integer与一个new Integer比较,就算值相等也不相等,new就是新的地址
- 如果两个Integer类型比较,只要再-128,127返回之间就相等 ,因为返回都是缓冲区对象,如果超过范围,返回new Integer(数据),所以不相等
public class DataDemo02 {
public static void main(String[] args) {
int i1 = 127;
int i2 = 127;
Integer i3 = 127;
Integer i4 = 127;
Integer i5 = new Integer(127);
Integer i6 = new Integer(127);
//自动装箱: Integer.valueOf(128)
Integer i7 = 128;
Integer i8 = 128;
System.out.println(i1 == i2); //true
System.out.println(i3 == i4); //true
System.out.println(i1 == i3); //true
System.out.println(i5 == i6); //false
System.out.println(i1 == i6); //true
System.out.println(i3 == i6); //false
System.out.println(i7 == i8); //false
//Double.valueOf()
Double d1 = 1.0;
Double d2 = 1.0;
System.out.println(d1 == d2); //false
}
}