包装类
八大基本类型 | 对应的封装类 |
---|---|
boolean | Boolean |
byte | Byte |
char | Char |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
void | Void |
基本关系
基本数据类型---->引用数据类型(对应封装类)---->继承Number---->继承Object
- 为什么引用包装类
- Java作为面向对象语言,往往我们需要操作的是类,将基本类型封装成对应的封装类,就是为了方便某些属性和方法;
- 我们常常需要使用集合,而集合特点之一就是只能存放引用数据类型。
Integer类
特点
- Integer 类在lang 包下
- Integer 底层还是一个操控一个int 类型数据,并对这个给数据进行封装
- Integer 类只有有参构造,参数可以是int类型和string类型
注意
public class Pack {
public static void main(String[] args) {
Integer i1 = new Integer("12");
Integer i2 = new Integer("ab");
}
}
同样是传入string类型参数,为什么"ab"报出 NumberFormatException(数字格式异常)呢?
这是因为ParseInt(string转int方法)抛出了异常
- 自动装箱
public class Pack {
public static void main(String[] args) {
Integer i1 = 13; //自动装箱
}
}
在生成的class文件中,我们可以看到执行了
Integer i1 = Integer.valueOf(13); 将int类型转换成Integer类型
- 自动拆箱
public class Pack {
public static void main(String[] args) {
Integer i1 = 12;
int i2 = i1; //自动拆箱
}
}
常用方法
- equals
public class Pack {
public static void main(String[] args) {
Integer i1 = new Integer(12);
Integer i2 = new Integer(12);
System.out.println(i1.equals(i2));
System.out.println(i1==i2);
}
}
可以看到两次输出结果不同,这是因为i1,i2指向的地址不同,因此i1==i2输出结果为false,而i1.equals(i2)比较的是两者指向内容,所以结果相同
特别注意的是,当我们使用自动装箱定义时,会有意想不到的结果
如:
public class Pack {
public static void main(String[] args) {
Integer i1 = 13; //自动装箱
Integer i2 = 13;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
解释
可以看到两次的结果竟然不同,这是因为在前面自动装箱介绍中知道,当我们我们以自动装箱方式定义时,编译器会自动帮我们调用valueOf方法,将类型转为Integer类型,我们再来看看valueOf方法
可以看到当传入的值为大于等于low(-128)时小于等于high(127)时,会直接返回cache数组内容,而cache数组内容就是(-128-127),所以当我们传入这个范围内的数,valueOf方法直接返回cache数组的内容,所以i1 ==i2输出结果为true;当传入得数不在范围,会在内存创建,即(new Integer(i)),因此i3 == i4输出结果为false.
-
compareTo
比较两个大小,返回值为类型int,值为1,0,-1
分别表示,大于,等于,小于 -
Intvalue
public class Pack {
public static void main(String[] args) {
Integer i1 = new Integer(12);
int i2 = i1.intValue();
}
}
将Integer类型转int类型
- parseInt
public class Pack {
public static void main(String[] args) {
int a = Integer.parseInt("12");
System.out.println(a);
}
}
将string类型转int类型
- toString
public class Pack {
public static void main(String[] args) {
String s = Integer.toString(1);
System.out.println(s);
}
}
int 类型转string类型
- valueOf
public class Pack {
public static void main(String[] args) {
String s = "12";
int a = 12;
System.out.println(Integer.valueOf(s));
System.out.println(Integer.valueOf(a));
}
}
其他类型转Integer类型