我需要一些幫助。這裏的實際情況是,程序I代碼將讀取多個文本文件,每個文本文件具有不同的字數。我想將這些單詞保留爲二維數組列表,因爲它根據當前存在的文本文檔數量和每個文本文檔中的單詞數量提供動態大小。我的二維ArrayList輸出給出累積值?
但是,經過多次測試後,給出的輸出結果並不如我預期的那樣。爲了使事情更簡單,我將此示例代碼作爲參考。我如何使用2D ArrayList與用於實際案例的方式相同。
ArrayList<List<String>> twoDWords = new ArrayList<List<String>>();
List<String> oneDword = new ArrayList<String>();
String word = "";
String[] words = new String[5];
System.out.println("Want like these(Using 2D ArrayList):");
for(int i = 0; i< 5; i++)
{
System.out.print("Array - "+i +": ");
word += "myArray ";
words[i] = word;
System.out.println(word);
}
System.out.println("\nBut Get these output:");
for(int i = 0; i< 5; i++)
{
oneDword.add(words[i]);
twoDWords.add(oneDword);
//oneDword.clear();
}
for(int i = 0; i< twoDWords.size(); i++)
{
System.out.print("Array - "+i +": ");
for(int j = 0; j< twoDWords.get(i).size(); j++)
{
System.out.print(twoDWords.get(i).get(j)+" ");
}
System.out.println("");
}
輸出看起來像它給出了最新的累積值只重複。正如你在代碼中看到的,我也嘗試使用clear()方法來重置數組,但是它會給出空值。
我希望有人能幫助我解決這個問題。在此先感謝〜