1. 借助JDK文档, 选取String与StringBuffer 、StringBuilder的常用API,并编写实例测试API的功能。
String常用API
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
**/
String a="123";
String b="123";
System.out.println(a.equals(b));
StringBuffer常用API
StringBuffer buffer = new StringBuffer();
buffer.append(89);
StringBuffer buffer = new StringBuffer("abc");
buffer.capacity();
StringBuffer buffer = new StringBuffer("abc");
buffer.charAt(1);
StringBuilder常用API
StringBuilder bu = new StringBuilder();
bu.append("abc");
bu.append(111);
bu.append(true)
bu.append('中');
bu.append(3.1415);
System.out.println(bu);// abc111true中3.1415
bu.append("abc").append(111).append(true).append('中').append(3.1415);
System.out.println(bu);//abc111true中3.1415
2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
String:字符串常量
StringBuffer:字符串变量
StringBuilder:字符串变量
StringBuilder:线程非安全的
StringBuffer:线程安全的
三者在执行速度方面比较:StringBuilder>StringBuffer>String
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
效率低下,需要一直创建新的对象,浪费大量空间资源且费时。