一.包装类
包装类:将基本类型封装到一个类中,包含属性和方法
使用:在使用过程中,会涉及到自动装箱和自动拆箱
装箱:将基本数据类型转换成包装类
拆箱:将包装类转换成基本数据类型
1 public class IntegerDemo { 2 public static void main(String[] args) { 3 int a = 10; 4 Integer i = new Integer(10); 5 //将int类型转换为Integer类型 6 Integer i1 = Integer.valueOf(a); 7 //将Integer类型转换为int类型 8 int i2 = i.intValue(); 9 } 10 } 11 1.将基本数据类型转换为对应的包装类:XXX.ValueOf(基本数据类型的值) 12 2.将包装类转换为对应的基本数据类型:包装类变量.XXXValue()
二.字符串
存储空间:字符串存放在常量池中,在jdk1.7之后(包括1.7),常量池放置在了堆空间中
创建方式:
1.String str = "abc";
2.String str1 = new String("abc");
字符串的本质:
1.在源码中有这样一行代码:private final char value[]; 这行代码说明字符串是一个字符数组
2.String类使用final修饰,不可以被继承
3.使用equals方法比较的是字符数组的每一个位置的值
字符串相关方法:
1 equals():比较的是字符数组每一个位置的值 2 public boolean equals(Object anObject) { 3 if (this == anObject) { 判断地址值是否相等 4 return true; 5 } 6 if (anObject instanceof String) { 判断传入字符串是否是String类型 7 String anotherString = (String)anObject; 8 int n = count; 9 if (n == anotherString.count) { 判断二者长度是否相同 10 char v1[] = value; 将字符串放入字符数组 11 char v2[] = anotherString.value; 将字符串放入字符数组 12 int i = offset; 13 int j = anotherString.offset; 14 while (n-- != 0) { 15 if (v1[i++] != v2[j++]) 两个数组取相同位置值,判断字符是否相等 16 return false; 若不相等返回false 17 } 18 return true; 19 } 20 } 21 return false; 22 }
1 hashCode():计算哈希值 2 public int hashCode() { 3 int h = hash; 点进去hash可以看到hash的初始值为0 4 if (h == 0 && value.length > 0) { 5 char val[] = value; 6 7 for (int i = 0; i < value.length; i++) { 对字符数组进行循环 8 h = 31*h + val[i]; var[i]是一个字符,可以当成int值进行计算,所以该方法的返回值类型是int 9 } 10 hash = h; 11 } 12 return h; 13 }
1 intern(): 2 public static void main(String[] args) { 3 4 String a = "abc"; 5 String aa = new String("abc"); 6 System.out.println(a == aa); 7 } 8 输出结果:false 9 若加一句代码: 10 public static void main(String[] args) { 11 12 String a = "abc"; 13 String aa = new String("abc"); 14 aa = aa.intern(); 15 System.out.println(a == aa); 16 } 17 此时,输出结果为:true 18 19 api文档中这样解释该方法: 20 when the intern method is invoked, 21 if the pool already contains a string equal to this String object as determined by the equals(Object)method, 22 then the string from the pool is returned 23 这句话翻译过来是: 24 当该方法被调用时,若常量池中已经包含了一个String,并且equals那个String对象时,常量池中的String就会被return(return的实际上是地址),即将常量池中地址返回给aa,这时a与aa对象的地址值就相同了,所以最终结果为true
char charAt(int index):返回字符串中第index个字符
boolean equalsLgnoreCase(String other):字符串忽略大小写比较
int indexOf(String str):返回指定字符的下标
String replace(char oldChar,char newChar):替换字符
boolean startWith(String prefix):若字符串以prefix开头返回true
boolean endWith(String prefix):若字符串以prefix结尾返回true
String subString(int beginIndex):从beginIndex开始截取旧字符串
String subString(int beginIndex,int endIndex):从beginIndex开始,endIndex截止截取旧字符串
String toLowerCase():将字符串中所有大写字母变为小写
String toUpperCase():将字符串中所有小写字母变为大写
String trim():删除字符串头部和尾部的空格