目录
1:基本数据类型包装类
注意:每个基本数据类型都有一个与之匹配的包装类。
1.1八大基本数据类型的包装类
注意:int的包装类的写法为Integer、char的包装类的写法是:Character
其余基本数据类型的包装类均是基本类型的首字母大写。
1.2:包装类的层次结构
1.3:包装类中的常用方法
装箱:把基本数据类型包装为对应的包装类对象
1、 Integer i1 = new Integer(10); // 利用构造方法
2、 Integer i2 = Integer.valueOf(10); //利用包装类中的静态方法
拆箱:把包装类对象转换为对应的基本数据类型。
1、int i3= i1.intValue(); //返回包装类对象i1对应的基本数据
public class NumberWrap {
public static void main(String[] args) {
String str = args[0];
//------------- String转换成Integer
Integer integer = new Integer(str); // 方式一
// Integer integer = Integer.valueOf(str); //方式二
//------------- Ingeter转换成String
String str2 = integer.toString();
//------------- 把integer转换成int
int i = integer.intValue();
//------------- 把int转换成Integer
Integer integer2 = new Integer(i);//
//Integer integer2 = Integer.valueOf(i);
//------------- String转换成int
int i2 = Integer.parseInt(str);
//------------- 把int转换成String
String str3 = String.valueOf(i2); // 方式一
String str4 = i2 + ""; // 方式二
}
1.4:自动装箱和自动拆箱
前面的装箱和拆箱操作,相对较麻烦。自jdk1.5开始,java增加的对基本数据类型的自动装箱和自动拆箱操作。
java编译器在编译时期会根据源代码的语法来决定是否进行装箱或拆箱。
1、 自动装箱:可以直接把一个基本数据类型赋值给包装类
例如: Double d = 3.3; //自动装箱操作
2、 自动拆箱:可以直接把一个包装类对象,赋值给基本类型
例如:int a = new Integer(3); //自动拆箱。
自动装箱和自动拆箱,简化了对包装类的操作。
1.5:为何需要包装类的使用和用处
int age = null; 改成 Integer age = null ;
基本数据类型int不能赋值为null,需要使用Integer来代替
List list = new ArrayList<Long>();
对于泛型之中只能放包装数据类型
用处:使用包装类处理数据更加的方便
在后期中的集合在使用的时候,集合保存的数据只能是包装类型,不能使用基本的数据类型。
1.6:总结
1:每个基础数据类型都会有相应的包装类型,大多是是首字母大写,int的包装类的写法为Integer、char的包装类的写法是:Character
2:Object是基类
3:装箱:基础数据类型转换为包装类---利用构造方法、利用包装类中的静态方法
拆箱:包装类转换为基础数据类型--eg.--int i3= i1.intValue(); //返回包装类对象i1对应的基本数据
4:了解自动装箱和拆箱
5:包装类能做到基础类型不能做的事情---eg. --将null能赋值给Integer但不能给int
1.7:建议采纳
如有建议或者错误请私信我进行修改,感谢!!!