- 借助JDK文档, 选取String与StringBuffer 、StringBuilder的常用API,并编写实例测试API的功能。
1、String对象的构造和初始化
public String(String original)
初始化新创建的String对象,使其表示与参数相同的字符序列; 换句话说,新创建的字符串是参数字符串的副本。 除非需要original的显式副本, original使用此构造函数是不必要的,因为Strings是不可变的。
String s1 = "abc";//字符串常量池
String s3 = "abc";
String s2 = new String(“abc");
String s4 = new String(“abc");
System.out.println(s1==s2); // false
System.out.println(s1==s3); // true
System.out.println(s1.equals(s3)); // true
System.out.println(s2==s4); // false
System.out.println(s2.equals(s4)); // true
2.StringBuffer
StringBuffer()的方法:
public StringBuffer()
构造一个没有字符的字符串缓冲区,初始容量为16个字符。
public int Capacity();返回当前容量 理论值
public int length() 返回长度(字符数) 实际值
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
System.out.println("sb:"+sb);
System.out.println("sb.capacity():"+sb.capacity());
System.out.println("sb.length():"+sb.length());
}
}
输出结果:
sb.capacity():50
sb.length():0
3.StringBuilder
public class Demo {
public static void main(String[] args) {
//String->StringBuilder
String str = "hello";
StringBuilder bu = new StringBuilder(str);
//往StringBuilder中添加数据
bu.append("world");
System.out.println("StringBuilder:" + bu);
//StringBuilder->String
String s = bu.toString();
System.out.println("字符串:" + s);
}
}
输出结果:
StringBuilder:helloworld
字符串:helloworld
- 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
String、StringBuffer、StringBuilder 比较:
String、StringBuffer、StringBuilder相同点
1). 内部实现基于字符数组,封装了对字符串处理的各种操作
2). 可自动检测数组越界等运行时异常
String、StringBuffer、StringBuilder不同点
1). String内部实现基于常量字符数组,内容不可变;
StringBuffer、StringBuilder基于普通字符数组,数组大小可根据
字符串的实际长度自动扩容,内容可变
2). 性能方面,对于字符串的处理,相对来说
StringBuilder > StringBuffer > String
3). StringBuffer线程安全;StringBuilder非线程安全
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
答. 反编译后的代码,在for循环中,每次都是new了一个StringBuilder,然后再把String转成StringBuilder,再进行append。而频繁的新建对象当然要耗费很多时间了,不仅仅会耗费时间,频繁的创建对象,还会造成内存资源的浪费,降低了效率。