包装类图解
装箱与拆箱
装箱:把基本类型的数据,包装到包装类中(基本数据类型=>包装类)
构造方法(已过时):Integer(int value)构造一个新分配的Integer对象,它表示指定的int值
Integer(String s)构造一个新分配的Integer对象,它表示String参数所指示的int值;传递的字符串,必须是基本类型的字符串,否则会抛出异常
public class IntegerClass {
public static void main(String[] args) {
Integer integer1 = new Integer(1);
System.out.println(integer1);
Integer integer2 = new Integer("1");
System.out.println(integer2);
}
}
静态方法:static Integer valueOf(int i)返回一个表示指定的int值的Integer实例
static Integer valueOf(String s)返回保存指定的String的值的Integer对象
public class IntegerClass {
public static void main(String[] args) {
Integer integer3 = Integer.valueOf(1);
System.out.println(integer3);
Integer integer4 = Integer.valueOf("1");
System.out.println(integer4);
}
}
拆箱:在包装类中取出基本类型的数据(包装类=>基本类型的数据)
成员方法:
int intValue() 以int 类型返回该Integer的值
public class IntegerClass {
public static void main(String[] args) {
Integer integer3 = Integer.valueOf(1);
int i = integer3.intValue();
System.out.println(i);
}
}
自动装箱与自动拆箱
概念:基本类型的数据和包装类之间可以自动的相互转换(JDK1.5+之后才有的特性)
自动装箱:直接把int类型的整数赋值给包装类
public class NewDemo {
public static void main(String[] args) {
Integer in = 1; //相当于Integer in = new Integer(1);
}
}
自动拆箱:in是包装类,无法直接参与运算,可以自动转换为基本类型的数据,再参与计算
public class NewDemo {
public static void main(String[] args) {
Integer in = 1;
in = in + 2; //in.intValue() + 2 = 3,in = in +2相当于in = new Integer(3)
System.out.println(in);
}
}
public class NewDemo {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1); //自动装箱 list.add(new Integer(1));
int a = arr.get(0);//自动拆箱 list.get(0).intValue();
}
}
基本类型与字符串类型的转换
1.基本类型=>字符串
基本数据的值 + “”(最简单的方式)
包装类中的静态方法:static String toString(int i)返回一个表示指定整数的String对象
使用String类的静态方法:static String valueOf(int i)返回int参数的字符串表示形式
public class NewDemo {
public static void main(String[] args) {
String s1 = 100 + "";
System.out.println(s1 + 200); //100200
String s2 = Integer.toString(100);
System.out.println(s2 + 200); //100200
String s3 = String.valueOf(100);
System.out.println(s3 + 200);
}
}
2.字符串=>基本类型
使用包装类的静态方法parsexx(“字符串”)
Integer类 static int parseInt(String s)
…
public class NewDemo {
public static void main(String[] args) {
int i = Integer.parseInt("100");
System.out.println(i + 200);
}
}