我正在讨论如何在
Java中使用Strings和StringBuffers.在这两个例子的每一个中创建了多少个对象?
例1:
String s = "a"; s = s + "b"; s = s + "c";
例2:
StringBuilder sb = new StringBuilder("a"); sb.append("b"); sb.append("c");
在我看来,Ex 1将创建5,而Ex 2将创建4个对象.
解决方法
您可以通过分析java字节码来确定答案(使用javap -c).示例1创建了两个StringBuilder对象(参见第4行)和两个String对象(参见第7行),而示例2创建了一个StringBuilder对象(参见第2行).
请注意,您还必须考虑char []对象(因为数组是Java中的对象). String和StringBuilder对象都使用底层char []实现.因此,示例1创建了八个对象,示例2创建了两个对象.
例1:
public static void main(java.lang.String[]); Code: 0: ldc #2; //String a 2: astore_1 3: new #3; //class java/lang/StringBuilder 6: dup 7: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V 10: aload_1 11: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 14: ldc #6; //String b 16: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 19: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 22: astore_1 23: new #3; //class java/lang/StringBuilder 26: dup 27: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V 30: aload_1 31: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 34: ldc #8; //String c 36: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 39: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 42: astore_1 43: return }
例2:
public static void main(java.lang.String[]); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: ldc #3; //String a 6: invokespecial #4; //Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V 9: astore_1 10: aload_1 11: ldc #5; //String b 13: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 16: pop 17: aload_1 18: ldc #7; //String c 20: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 23: pop 24: return }