String相关类
String
1.String是不可变的字符数列,因为源码加了final修饰。
2.字符串比较
最好用equals方法(如果不明白,请看面向对象的==与equals)。
package com.itcode.demo4;
/**
* @Auther: 成都码到功成学员
* @Description:
* String类测试
*/
public class TestWrapper3 {
public static void main(String[] args) {
//
String a = "码到功成";
String b = "码到" + "功成";// 编译器自动优化拼接变成"码到功成"
System.out.println(a==b);// true
String c = "码到";
String d = "功成";
String e = c + d;
System.out.println(e==a);//false
}
}
StringBuffer和StringBuilder
概述:是可变的字符数列。StringBuffer和StringBuilder都继承了抽象类AbstractStringBuilder,源码中 ,没有加final修饰。它们的区别是:
StringBuffer:安全,效率低。
StringBuilder:不安全,效率高(一般使用这个)。
示例:
package com.itcode.demo4;
/**
* @Auther: 成都码到功成学员
* @Description:
* StringBuffer类测试
*/
public class TestWrapper4 {
public static void main(String[] args) {
//
StringBuffer sb = new StringBuffer("abc123");
System.out.println(sb);
System.out.println(Integer.toHexString(sb.hashCode()));//打印哈希值
sb.setCharAt(2,'S');//把下标2的值替换为S
System.out.println(sb);
System.out.println(Integer.toHexString(sb.hashCode()));
}
}
效果:

看哈希值都是1b6d356。
常用方法
StringBuffer和StirngBuilder的方法几乎一模一样。
它们有些方法和String类似,比如: indexOf(String str)、indexOf(String str, int fromIndex)、length()、charAt(int index)、substring(int start, int end)、substring(int start)。
特有方法请看代码示例:
package com.itcode.demo4;
/**
* @Auther: 成都码到功成学员
* @Description:
* StringBuffer和StringBuilder类测试
*/
public class TestWrapper4 {
public static void main(String[] args) {
//
StringBuilder sb = new StringBuilder();
// 打印26个字母
for (int i=0; i<26;i++){
sb.append((char)('a'+i));
}
System.out.println(sb);
System.out.println(sb.reverse());//反转
sb.setCharAt(1, '好');// 替换
System.out.println(sb);
sb.insert(0, "成都").insert(1,"码到功成");// 插入
System.out.println(sb);
sb.delete(5, 10);// 删除
System.out.println(sb);
}
}
效果:

时间内存对比
可变比不可变更不占空间和耗用内存。
示例:
package com.itcode.demo4;
/**
* @Auther: 成都码到功成学员
* @Description:
* 测试String和StringBuilder做一样的事占用内存和时间比较
*/
public class TestWrapper5 {
public static void main(String[] args) {
// String
String s = "";
long num1 = Runtime.getRuntime().freeMemory();// 测试内存
long time1 = System.currentTimeMillis();// 获取时间毫秒值
for(int i=0; i<5000;i++){
s += i;//相当于创建10000个对象
}
long num2 = Runtime.getRuntime().freeMemory();// 测试内存
long time2 = System.currentTimeMillis();// 获取时间毫秒值
System.out.println("String所占内存:"+(num1-num2));
System.out.println("String所花时间:"+(time2-time1));
// String
StringBuilder sb = new StringBuilder();
long num3 = Runtime.getRuntime().freeMemory();// 测试内存
long time3 = System.currentTimeMillis();// 获取时间毫秒值
for(int i=0; i<5000;i++){
sb.append(i);
}
long num4 = Runtime.getRuntime().freeMemory();// 测试内存
long time4 = System.currentTimeMillis();// 获取时间毫秒值
System.out.println("StringBuilder所占内存:"+(num3-num4));
System.out.println("StringBuilder所花时间:"+(time4-time3));
}
}
效果:

Last updated
Was this helpful?