1、不可变String
2、重载“+”与StringBuider
案例一:
/** * 本例主要讲解字符串的不可变性: * String字符串一旦创建,就不会发生变化。 */ public class StringTest { /** * 实现字符串转大写 * @param string * @return */ public static String upcase(String string){ return string.toUpperCase(); } public static void main(String[]args){ String s = "string-test"; System.out.println(s);//string-test String q = upcase(s); System.out.println(q);//STRING-TEST System.out.println(s);//string-test } } |
案例二
public class StringConcatenation { public String implicit(String[] fields){ String result=""; for(int i=0;i<fields.length;i++){ result+=fields[i]; } return result; } /** * 利用StringBuilder连接字符串的效率高一些 * @param fields * @return */ public String explicit(String[] fields){ StringBuilder result = new StringBuilder(); for(int i=0;i<fields.length;i++){ result.append(fields[i]); } return result.toString();//可变字符串变成不变字符串 } public static void main(String[] args){ StringConcatenation string = new StringConcatenation(); String [] str ={"hello "," welcome"," study"," string"," and"," stringBuilder"}; String str2 = string.implicit(str); System.out.println(str2); String str3 = string.explicit(str); System.out.println(str3); } } |
import java.util.Random; public class StringBuilderTest { Random ran = new Random(47); public String toString(){ StringBuilder result = new StringBuilder("["); for(int i=0;i<25;i++){ result.append(ran.nextInt(100)); result.append(","); } //删除最后一个逗号 result.delete(result.length()-1,result.length()); result.append("]"); return result.toString(); } public static void main(String[]args){ StringBuilderTest stringBuilderTest = new StringBuilderTest(); System.out.println(stringBuilderTest); } } |