快捷搜索: 王者荣耀 脱发

包装类(Wrapper)的使用

包装类的使用:

    基本数据类型包装成包装类的实例——装箱 通过包装类的构造器实现: int i = 500; Integer i = new Integer(i); 还可以通过字符串参数构造包装类对象: Float f = new Float(“4.57”); Long l = new Long(“asdf”);//NumberFormatException 获得包装类对象中包装的基本类型变量——拆箱 调用包装类的.xxxValue()方法 boolean b = bObj.booleanValue(); 注意:JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配。 字符串转换成基本数据类型 通过包装类的构造器实现 int i = new Integer(“12”); 通过包装类的parseXxx(String s)静态方法: Float f = Float.parseFloat(“12.1”); 基本数据类型、包装类,转换成字符串 调用字符串重载的valueOf()方法: String fstr = String.valueOf(2.34f); 更直接的方法: String inStr = 5 + " ";

自动装箱

    不需要显式使用构造器。 Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[ ],保存了从-128 ——127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在-128——127范围内时,可以直接使用数组中的元素,不用再去new了。目的:提高效率
int num = 10;
Integer in1 = num;//自动装箱
boolean b1 = true;
Boolean b2 = b1;//自动装箱
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true
Integer y = 128;
Integer x = 128;
System.out.println(x == y);//false

自动拆箱

int i = 10;
Integer in1 = i;//自动装箱
int i2 = in1;//自动拆箱
经验分享 程序员 微信小程序 职场和发展