定义
包装类就是将基本数据类型封装到类中,目的是为了让基本类型也能让Object来接收。
class IntDemo {
private int intValue;
public IntDemo(int intValue) {
this.intValue = intValue;
}
public int intValue() {
return this.intValue;
}
}
public class Test {
public static void main(String[] args) throws Exception {
// 将整型常量封装到类中
IntDemo intDemo = new IntDemo(10);
int result = intDemo.intValue();
System.out.println(result);
Object obj = new IntDemo(5);
IntDemo temp = (IntDemo) obj;
System.out.println(temp.intValue());
}
}
分类
-
对象型包装类(Object的直接子类):Boolean(boolean)、Character(char)
-
数值型包装类(Number的直接子类,存在数值转换异常):Byte(byte)、Short(short)、Long(long)、Double(double)、Float(float)、Integer(int)
装箱与拆箱—基本数据类型与相应包装类的数据处理
public class Test {
public static void main(String[] args) throws Exception {
// 装箱
Integer i = new Integer(10);
// 拆箱
int result = i.intValue();
System.out.println(result+10);
// 自动装箱
Integer i2 = 20;
// 自动拆箱
int result2 = i2+10;
System.out.println(result2+10);
}
}
阿里编码规范:所有相同类型的包装类对象之间的值比较,全部使用equals方法比较
public class Test {
public static void main(String[] args) throws Exception {
Integer i1 = new Integer(10);
Integer i2 = 10;
System.out.println(i1 == i2); // false
System.out.println(i1.equals(i2)); // true
}
}
说明:
对于Integer value = data
在-128~127之间的赋值,Integer对象在Integer常量池产生,会复用已有对象,这个区间内的Integer值可以直接使用==判断。除此之外的所有数据,都会在堆上产生,并不会复用已有对象。**
public class Test {
public static void main(String[] args) throws Exception {
Integer i1 = 10;
Integer i2 = new Integer(10);
Integer i3 = 10;
Integer i4 = 200;
Integer i5 = 200;
System.out.println(i1 == i2);
System.out.println(i1 == i3);
System.out.println(i4 == i5);
}
}
使用int 还是Integer?
-
[强制]所有POJO类(简单Java类:Bean,只有基本类型、构造方法、getter、setter)属性必须使用包装类型
-
[强制]RPC方法(远程方法调用)的返回值和参数必须使用包装类型
-
[推荐]所有的局部变量使用基本类型
字符串和基本类型的转换
public class Test {
public static void main(String[] args) throws Exception {
String str = "123";
int data = Integer.parseInt(str);
System.out.println(str+10);
System.out.println(data+10);
String str1 = "123.10";
double b = Double.parseDouble(str1);
System.out.println(b+10);
}
}
需要注意的是,将字符串转为数字的时候,字符串的组成有非数字,那么转换就会出现错误 NumberFormatException
(运行时异常)
public class Test {
public static void main(String[] args) throws Exception {
String str = "123a";
int data = Integer.parseInt(str);
System.out.println(data+10);
}
}
public class Test {
public static void main(String[] args) throws Exception {
String str1 = "true";
boolean b1 = Boolean.parseBoolean(str1);
System.out.println(b1);
String str2 = "true123";
boolean b2 = Boolean.parseBoolean(str2);
System.out.println(b2);
}
}
public class Test {
public static void main(String[] args) throws Exception {
String str = ""+123;
System.out.println(str.length());
}
}
- 使用String类的valueof(基本类型),此方法不产生垃圾空间(推荐,静态方法)
public class Test {
public static void main(String[] args) throws Exception {
String str = String.valueOf(10);
System.out.println(str);
}
}