包装类的粗浅记录

来源:互联网 发布:realtek pxe 网络唤醒 编辑:程序博客网 时间:2024/06/06 09:46

直接上代码,不多说。


//包装类测试说明public class WrapperTest {//Boolean包装类测试,该类内部有两个static final的Boolean引用TRUE和FALSEpublic void testBoolean(){//直接用基本类型赋值Boolean b1 = true;Boolean b2 = true;System.out.println(b1==b2); //基本类型走valueOf,直接返回输出TRUE和FALSE引用的对象,故输出trueBoolean b3 = Boolean.valueOf("true");System.out.println(b1==b3); //valueOf方法同上Boolean b4 = new Boolean("true");System.out.println(b2==b4);//新建对象,故false}public void testInteger(){//Byte类中有个ByteCache内部类,此中含static final Byte cache[]用于缓存-128~127的Byte对象Byte b1 = 55;Byte b2 = 55;//Byte b3 = 555; 因为取值范围限制,无法赋值System.out.println(b1==b2); //因基本类型走valueOf调缓存,故结果输出trueByte b3 = Byte.parseByte("55");System.out.println(b1==b3); //parseByte生成一个基本类型,往后同上,故结果输出trueByte b4 = Byte.valueOf("55");System.out.println(b1==b4); //还是会走parseByte最终同上,结果输出trueByte b5 = new Byte((byte)55);System.out.println(b1==b5); //新建对象,结果输出falseByte b6 = Byte.decode("55");System.out.println(b1==b6); //decode方法同,最终走valueOf,结果输出true// Short,Integer,Long也有同样缓存,故自动装箱时原理一致。}public void testDecimal(){// Float, Double无缓存,每次都是newFloat f1 = 0.13f;Float f2 = 0.13f;Double d1 = 0.13d;Double d2 = 0.13d;System.out.println(f1==f2);System.out.println(f1.equals(f2));System.out.println(d1==d2);System.out.println(d1.equals(d2));}public void testCharacter(){//缓存了0到127的char,即'\u0000'到'\u007F'。valueOf方法只能接受char基本类型,其他木油Character c1 = '\u007F';Character c2 = '\u007F';Character c3 = '\u0080';Character c4 = '\u0080';System.out.println(c1==c2);System.out.println(c3==c4);//其他方法还有很多,没空挨个看,怕瞎}}


0 0
原创粉丝点击