室友上个厕所的时间我居然学会了包装类?
博客主页 天道酬勤,勤能补拙,和小吴一起加油吧 大一新生,水平有限,恳请各位大佬指点,不胜感激! 🍊这里有一点路线小伙伴可以参考一下哈
拆箱与装箱
视频笔记:
基本数据类型包装成包装类的实例——装箱
1.通过包装类的构造器实现:
int i=100; Integer t=new Integer(i);
2. 通过字符串参数构造包装类对象:
Float f=new Float("2.22"); Long l=new Long("sa");
获得包装类对象中包装的基本类型变量——拆箱
调用包装类的.xxxValue()方法:
boolean b=bObj.booleanValue();
JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配。
下面看一段代码(基本数据类型------>包装类)
public class student { public static void main(String[] args) { int age=20; Integer m=new Integer(age); System.out.println(m.toString()); } }
也可以这样
public class student { public static void main(String[] args) { int age=20; Integer m=new Integer(age); System.out.println(m.toString()); Integer n=new Integer("222"); System.out.println(n.toString()); } }
但是使用第二种做法的时候,括号里只能写数字,如果在222后面加个字母a,就会报异常
不是任何情况下都不能加字母,只是要与其结构对应啦!
例如加上下面语句后
Float k=new Float(12.2f); System.out.println(k); Boolean b=new Boolean("tt22"); System.out.println(b);
下面看一段代码(包装类--------->基本数据类型)
public class student { public static void main(String[] args) { Integer m=new Integer(11); int a=m.intValue(); System.out.println(a); Float f=new Float(13.2); float f1=f.floatValue(); System.out.println(f1); } }
下面由于JDK5.0版本以后,方便很多步骤,直接自动装箱,拆箱;
自动装箱:
public class student { public static void main(String[] args) { int c=1; Integer c1=c; System.out.println(c1); } }
自动拆箱:
public class student { public static void main(String[] args) { int c=1; Integer c1=c; System.out.println(c1);//自动装箱 int c2=c1; System.out.println(c2);//自动拆箱 } }
基本数据类型与String之间的相互转换
1.连接运算
public class student { public static void main(String[] args) { int c=1; String str=c+" s "; System.out.print(str); } }
2.调用String的valueOf(Xxx xxx)
public class student { public static void main(String[] args) { float a1=22.2f; String ss=String.valueOf(a1); System.out.println(ss); } }
但是处理String转换为int又有些不一样
public class student { public static void main(String[] args) { String str="122"; //int a=(int)str;//错误 //Integer a1=(Integer)str;//错误 int A=Integer.parseInt(str); System.out.println(A); } }
注意:str复制的时候122后面不要带字母
包装类的有关面试题
1.一下两段代码的输出结果是否相同
Object a=true?new Integer(1):new Double(2.0); System.out.println(a);
Object b; if(true) b=new Integer(1); else b=new Double(2.0); System.out.println(b);
第一段代码在编译的时候要求:左边和右边必须统一,编译的时候会提升到1.0 第二段代码的形式则没有这种要求
2.
Integer i=new Integer(10); Integer j=new Integer(10); System.out.println(i==j);//false 不是同一个对象 Integer m=1; Integer n=1; System.out.println(m==n);//True Integer a=128; Integer b=128; System.out.println(a==b);//false
当a=127,b=127时
Integer a=127; Integer b=127; System.out.println(a==b);
这里面a,b只有满足大于等于-128小于等于127才可以省略构造过程,得到true 也就是如果我们使用自动装箱的方式,给Integer赋值的范围在-128到127内,可以直接使用数组中的元素,不用再去new了,提高效率(可以参考API)
学习如逆水行舟,不进则退。和小吴一起加油吧!
上一篇:
通过多线程提高代码的执行效率例子