所以我希望能够在 Java 中拥有一组可变字符串。
我有这个测试类来查看不可变字符串的功能:
public class GetStringTest
{
private Vector<String> m_stringList;
public GetStringTest()
{
m_stringList = new Vector<String>();
m_stringList.add("zero");
m_stringList.add("one");
m_stringList.add("two");
m_stringList.add("three");
m_stringList.add("four");
m_stringList.add("five");
m_stringList.add("six");
}
public String getString(int index)
{
return m_stringList.get(index);
}
public String toString()
{
String str = "";
for (String item : m_stringList)
{
str += item + "\n";
}
return str;
}
public static void main(String[] args)
{
GetStringTest gst = new GetStringTest();
System.out.println("=== original content ===");
System.out.println(gst);
String strToChange = gst.getString(2); // "two"
strToChange = "eleventy-one";
System.out.println("=== with change ===");
System.out.println(gst);
}
}
以下是输出:
=== original content ===
zero
one
two
three
four
five
six
=== with change ===
zero
one
two
three
four
five
six
我该怎么做才能将这些字符串存储为可变的?我正在考虑有一个 StringObject 类,它只包含对 String 的引用。这是最好的选择吗?