字符串一旦定义不可改变:
字符串的底层实现实际上就是数组,如下为String的jdk源码:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}
缺陷为长度固定,字符串的内容是无法改变的,分析如下代码:
String str = "hello";
str = str + "world";
str += "!!!";
System.out.println(str);
运行截图:
分析内存图:
在此过程中,只是字符串引用对象发生改变,字符串内容没有发生改变。在以上代码的过程中不断的产生了垃圾。
总结:
- 字符串直接赋值
- 字符串使用equals()方法比较
- 字符串尽量别改变,否则会产生很多垃圾