String
String变量是不可变的,源码里面用了final修饰。
private final char value[];
String str = "Hello"; System.out.println(Integer.toHexString(str.hashCode())); str = "World"; //字符串一旦变化就会重写生成一个对象 System.out.println(Integer.toHexString(str.hashCode()));
//输出 42628b2 4fe2b72
StringBuilder线程不安全,但效率高,常用。
StringBuffer线程安全,但效率低。
StringBuilder sb = new StringBuilder("Hello"); System.out.println(Integer.toHexString(sb.hashCode())); sb.append(" World"); //追加 System.out.println(sb); System.out.println(Integer.toHexString(sb.hashCode()));
//输出 45ee12a7 Hello World 45ee12a7
public class Test { public static void main(String[] args) { String str1 = ""; long num1 = Runtime.getRuntime().freeMemory(); long num2 = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { str1 = str1 + i; } long num3 = Runtime.getRuntime().freeMemory(); long num4 = System.currentTimeMillis(); System.out.println("消耗内存:"+(num3-num1)); System.out.println("消耗时间:"+(num4-num2)); StringBuilder str2 = new StringBuilder(""); long num5 = Runtime.getRuntime().freeMemory(); long num6 = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { str2.append(i); } long num7 = Runtime.getRuntime().freeMemory(); long num8 = System.currentTimeMillis(); System.out.println("消耗内存:"+(num7-num3)); System.out.println("消耗时间:"+(num8-num4)); } }
//输出 消耗内存:-5895808 消耗时间:149 消耗内存:0 消耗时间:0