2016-09-15 46 views
0

我需要一些幫助。這裏的實際情況是,程序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(""); 
    } 

這是輸出: enter image description here

輸出看起來像它給出了最新的累積值只重複。正如你在代碼中看到的,我也嘗試使用clear()方法來重置數組,但是它會給出空值。

我希望有人能幫助我解決這個問題。在此先感謝〜

回答

1

添加到克里斯托弗的解決方案,你必須使用foreach循環,因爲它更容易閱讀:

for(int i = 0; i< 5; i++) 
{ 
    oneDword.add(words[i]); 
    twoDWords.add(oneDword); 
    oneDword = new ArrayList<String>(); // --> You need this since 'oneDword' contains the previous values as well and it'll keep adding new values to this list. 
    //oneDword.clear(); 
} 

for(List<String> al: twoDWords) { 
    for(String s: al) { 
    System.out.println(s); 
    } 
} 
1

它是存儲在您的數組twoDwords的每個元素中的非常相同的數組對象。你需要使用「新」的循環中,爲您的陣列twoDWords的每個元素的新數組:

.......... 
    for(int i = 0; i< 5; i++) 
     { oneDword = new ArrayList<String>(); //<------- 
      oneDword.add(words[i]); 
      twoDWords.add(oneDword); 
      //oneDword.clear(); 
     } 
    ......... 
1

要理解你在做什麼錯誤,你需要考慮方法參數引用。 專門這一行:

twoDWords.add(oneDword); 

在這一行要添加oneDword的「參考」你twoDWords列表。每次添加對同一個字的引用。因此,最終列表大小爲5,但它們都包含對您的oneDword列表的引用(您在中間循環中保持增長)。