三种字符串包装类
String 类
常用方法
1. 创建String对象:
// 使用字面量创建
String s1 = "hello";
// 使用new关键字创建
String s2 = new String("world");
当使用字面量创建String
对象时,JVM首先会检查字符串常量池中是否已经存在值为"hello"的String
对象。如果存在,JVM会直接返回该对象的引用,而不会创建新的对象。如果不存在,JVM会在字符串常量池中创建一个新的String
对象,并返回其引用。
当你使用new
关键字创建String
对象时,JVM会在堆内存中创建一个新的String
对象,不管字符串常量池中是否已经存在相同的String
对象。
2. 使用length()方法获取字符串长度:
String s = "hello";
int len = s.length(); // len的值为5
3. 使用charAt()方法获取指定位置的字符:
String s = "hello";
char c = s.charAt(1); // c的值为'e'
4. 使用substring()方法获取子字符串:
String s = "helloworld";
String sub = s.substring(0, 5); // sub的值为"hello"
5. 使用contains()方法检查字符串是否包含某个子串:
String s = "helloworld";
boolean contains = s.contains("world"); // contains的值为true
6. 使用equals()方法比较两个字符串是否相等:
String s1 = "hello";
String s2 = "world";
boolean equals = s1.equals(s2); // equals的值为false
7. 使用indexOf()方法查找字符或子串在字符串中的位置:
String s = "helloworld";
int index = s.indexOf('o'); // index的值为4
8. 使用replace()方法替换字符串中的字符或子串:
String s = "helloworld";
String replaced = s.replace('o', 'a'); // replaced的值为"hellawarld"
9. 使用valueOf()方法将其他类型的数据转换为字符串:
int i = 123;
String s = String.valueOf(i); // s的值为"123"
10. 使用+操作符或concat()方法连接字符串:
String s1 = "hello";
String s2 = "world";
String s3 = s1 + s2; // s3的值为"helloworld"
String s4 = s1.concat(s2); // s4的值为"helloworld"
StringBuffer 类
与
String
类不同,StringBuffer
是可变的,也就是说,你可以在创建StringBuffer
对象后修改它的内容。
常用方法
append()
: 添加字符串到当前StringBuffer
对象的末尾。insert()
: 在指定位置插入字符串。delete()
: 删除指定位置的字符。reverse()
: 反转当前StringBuffer
对象的内容。
StringBuffer sb = new StringBuffer("hello");
sb.append(" world"); // sb现在是"hello world"
sb.insert(5, ","); // sb现在是"hello, world"
sb.delete(5, 6); // sb现在是"helloworld"
sb.reverse(); // sb现在是"dlrowolleh"
StringBuffer与String对比
1)String保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低。
2)StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高
3)然而,StringBuffer
的可变性也是其一个缺点。由于StringBuffer
对象可以被修改,因此它们不是线程安全的。如果你在多线程环境中使用StringBuffer
,可能需要使用同步来防止并发修改。相反,由于String
对象是不可变的,它们是线程安全的。
StringBuilder 类
StringBuilder
与StringBuffer
非常相似,同样也是可变的,允许在创建后修改字符串的内容。它具有与StringBuffer
相同的API。
StringBuilder
和StringBuffer
的主要区别在于同步性:
StringBuffer
的所有主要操作都是同步的,是线程安全的。这意味着在多线程环境中,当一个线程正在修改StringBuffer
对象时,其他线程不能修改这个对象,必须等待。- 相反,
StringBuilder
的所有操作都是非同步的,不是线程安全的。这使得StringBuilder
在单线程环境中的性能比StringBuffer
更好,因为它避免了同步带来的开销。
因此,需要根据实际情况选择使用StringBuffer
还是StringBuilder
:
- 在多线程环境中,如果需要修改字符串,应该使用
StringBuffer
,以确保线程安全。 - 在单线程环境中,如果需要修改字符串,应该使用
StringBuilder
,以获取更好的性能。