一、包装类
package 类; public class TestInteger { public static void main(String[] args) { Integer i=new Integer(50);//从java9开始被废弃 Integer j=Integer.valueOf(10);//官方推荐 int a=j.intValue();//把包装类对象转为基本类型 double b=j.doubleValue(); //字符串转为数字 Integer m=Integer.valueOf("456"); //Integer n=Integer.valueOf("456adf");//NumberFormatException System.out.println(Integer.MAX_VALUE); /* 包装类的用途: 对于包装类来说,这些类的用途主要包含两种: 1.作为和基本类型对应的类型存在,方便涉及到对象的操作,如Object[],集合等的操作 2.包含每种基本数据类型的相关类型如最大值、最小值等,以及相关的操作方法(这些操作方法的作用是在基本数据类型、包装类对象、字符串之间提供了相互之间的转化!) */ } }
二、自动装箱拆箱
//测试自动装箱和拆箱 Integer x=100;//编译器:Integer x=Integer.valueOf(100); int y=x;//编译器: int y=x.intValue(); //很容易出现一些问题 // Integer z=null; // int z2=z;//编译器:int z2=z.intValue();//NullPointerException //包装类的缓存的问题 //自动装箱时,[-128,127]之间的数有缓存! Integer x1=100;//这样x1和x2是两个不同的对象 Integer x2=100; Integer x3=1000; Integer x4=1000; System.out.println(x1==x2);//true,按理x1和x2是两个不同的对象,不应该相等 System.out.println(x2==x4);//false System.out.println(x1.equals(x2));//true System.out.println(x3.equals(x4));//true
三、自定义包装类
p133+p134
四、String类的源码分析
字符相关类
String类代表不可变的字符序列
StringBuilder类和StringBuffer类代表可变字符序列
可变还是不可变 都是final的祸
String类对象代表不可变的Unicode字符序列,因此我们可以将String对象称为”不可变对象“。那什么叫做”不可变对象“呢?指的是对象内部的成员变量的值无法再改变。
package 类; public class TestString { public static void main(String[] args) { String s1=new String("abcdef"); String s2=s1.substring(2,4); //打印ab199863 System.out.println(Integer.toHexString(s1.hashCode())); //打印:c61,显然,s1和s2不是同一个对象 System.out.println(Integer.toHexString(s2.hashCode())); String str1="hello"+"java";//相当于str1="hello java"; String str2="hello java"; System.out.println(str1==str2);//true String str3="hello"; String str4="java"; //编译的时候不知道变量中存储的是什么,所以没办法在编译的时候被优化 String str5=str3+str4; System.out.println(str2==str5);//false } }
五、StringBuffer和stringBuilder可变字符序列
StringBuffer:线程安全,做线程同步检查,效率低
stringBuilder:线程不安全,不做线程同步检查,效率高,一般用这个
package 类; public class TestString1 { public static void main(String[] args) { String str="abc"; StringBuilder sb=new StringBuilder("abc"); StringBuffer sb2=new StringBuffer("abc"); } }