你是否真的会用==?
下面是我从别处看到的两段小代码,方知我了解的只是皮毛中的皮毛;
代码一:Integer a=128,b=128;
Integer c=100,d=100;
System.out.println(a==b);//false
System.out.println(c==d);//true
结果为false和true;
原因:abcd都是新建的对象,而==是比较两个对象的引用,按理都是false;为什么第二个是true?当我们声明Integer c=100时,会进行自动装箱,也就是把基本数据类型转换为Integer类型的对象,而转换成Integer对象则是调用了valueOf()方法将Integer中-128-127的值缓存了下来,当声明的Integer对象的值在-128-127时,引用的是同一个对象,所以结果是true;
代码二:Integer a1 = new Integer(128);
int b1 = 128;
Integer c1 = new Integer(10);
Integer d1 = new Integer(10);
System.out.println(a1==b1);
System.out.println(c1==d1);
结果是:true和false
原因是:注意b1这里是int类型,当int和Integer进行==比较的时候,Java会把Integer进行自动拆箱,也就是把Integer转成int类型,所以这里进行比较的是int类型的值,所以结果即为true。而c1和d1是new出来的两个不同的对象,故为false。
String、Integer、int之间的转换
String 转int;调用Integer.parseInt(String str);常用
>
String s5 = “23”;
int i5 = Integer.parseInt(s5);//String转基本类型
int 转String;调用Integer.toString(int i);常用
>
int i4 = 200;
String s4 = Integer.toString(i4);//基本数据转String
String 转包装类
>
String s3 =”123”;
Integer i3 = new Integer(s3);//String转包装类
包装类 转String
>
Integer i2 = 10;
String s2 = i2.toString();//包装类转String
int 转包装类-装箱
Integer i = new Integer(10);//装箱
Integer i2 = 10;
int a1 = i2.intValue();//拆箱,也可以a1=i,自动拆箱