1.包装类就是将基本数据类型封装到类中,这样就可以用Object类接收了。
范例:自己定义一个包装类
class intDemon{
private int intValue;
//通过构造方法封装
public intDemon(int intDemon) {
this.intValue = intDemon;
}
// 取出封装中的内容
public int getIntDemon() {
return intValue;
}
}
public class Test {
public static void main(String[] args) {
intDemon intDemon = new intDemon(10);
int result = intDemon.getIntDemon();
System.out.println(result);
}
}
这时候intDemon实际上就是int类型的包装类,利用intValue就可以实现基本数据类型变为对象的需求。
将基本数据类型包装成一个类对象的本质就是使用Object进行接收处理。
2. 装箱与拆箱
在包装类与基本数据类型处理中有两个概念:
装箱:将基本数据类型变为包装类对象,利用每一个包装类提供的构造方法实现装箱处理。
拆箱:将包装类中包装的基本数据类型取出。
范例:以int和Integer举例
public class Test{
public static void main(String[] args) {
//手动装箱
Integer i = new Integer(10);
//手动拆箱
int result = i.intValue();
System.out.println(result+10);
// 自动装箱
Integer i1 = 20;
//自动拆箱
int result1 = i1+10;
System.out.println(result1);
}
}
这时候就会存在“==”和"equals"问题
看下面例子:
public class Test{
public static void main(String[] args) {
Integer i1 = new Integer(10);
Integer i2 = 10;
System.out.println(i1 == i2); // false
System.out.println(i1.equals(i2)); // true
}
}
第一个输出为false是因为两者都是对象,比较的是内存地址,故不相等。
阿里编码规范:所有相同类型的包装类对象之间值的比较,全部使用equals方法。
3. 字符串与基本类型的转换
3.1 将字符串转为基本类型(静态方法)
调用各个包装类:parseXX(String str)
Integer.parselnt(String str);
Double.parseDouble(String str);
public class Test{
public static void main(String[] args){
String str = "123";
int i = Integer.parseInt(str); //将String类型变为int
System.out.println(i+10); //输出133,若为字符串则为12310
String str1 = "123.10";
double b = Double.parseDouble(str1); //将字符串类型变为double
System.out.println(str1+10); //输出123.1010
System.out.println(b+10); //输出为133.1
}
}
public class Test13{
public static void main(String[] args){
String str = "123a"; //既有数字又有字母,存在数值转换异常
int i = Integer.parseInt(1);
}
}
3.2 基本类型变为字符串
a. “”+基本类型
public class Test{
public static void main(String[] args){
String str = ""+123; //空白字符串+123变为字符串123
System.out.println(str.length()); //输出为3
}
}
b.使用String类的valueof(基本类型,静态方法),此方法不产生垃圾空间(推荐)
public class Test13{
public static void main(String[] args){
String str = String.valueOf(10); //将10变为字符串类型
System.out.println(str+10);//输出为1010
}
}