2016-12-29 170 views
-1

試圖從LinkedList中刪除某些單詞。這是我用於測試的數據:
String[] stopwords = {"the","and"};
nwl = LinkedList<String>(Arrays.asList(input));
String input = "the and of the "
我希望得到的結果是:[of]但我正在逐漸:[the, end, of, the]如何遍歷LinkedList並從Java中刪除某些單詞

for (Iterator<String> iter = nwl.iterator(); iter.hasNext();) { 
    String word = iter.next(); 
    for (int i = 0; i < nwl.size(); i++){ 
     if(word == stopwords[i]) { 
     iter.remove(); 
     } 
    } 
} 
+0

,如果你想,如果你想刪除重複使用'Set' **'iterate' **和刪除使用'Iterator'但首先決定你的操作 – emotionlessbananas

+0

@FlyingZombie感謝您的評論。我想保留重複的內容,這就是爲什麼我不使用'Set'。 –

+0

雖然最初這個問題似乎是關於字符串比較,但在更仔細的檢查中,它也是關於字符串分割/集合初始化。 –

回答

0

當你比較字符串,你需要使用.equals()方法,而不是==操作。因此,您需要將if (word == stopwords[i])更改爲if(word.equals(stopwords[i]))

加長版:

粗略地講,在==運營商確定兩個變量指向同一對象(在我們的例子:是否word,並在同一字符串對象stopwords[i]點)。 .equals()方法確定兩個對象是否相同(內容明智)。如果你的情況下程序無法產生所需的輸出,因爲你有兩個不同的字符串持有相同的內容。因此,通過==比較它們產生false,而通過.equals()比較它們會產生「真實」。

編輯

看了張貼在鏈接的程序,我發現了幾件事情:首先,內部的循環的條件,就必須改變以i < stopwords.length。其次,newWordList對象未正確初始化。這是新的LinkedList<String>(Arrays.asList(parts))這意味着LinkedList將包含一個值爲the and of the的String元素,這不是您想要的。您想要的LinkedList包含字符串元素如下:

  • 元素0:the
  • 元件1:and
  • 元件2:of
  • 元件3:the

因此初始化需要更改爲new LinkedList<String>( Arrays.asList(parts.split(" ")))。具體而言,parts.split(" ")將給定的字符串(split)拆分爲單獨的單詞,返回這些單詞的數組。

public static void main (String[] args) throws java.lang.Exception 
{ 
    String[] stopwords = { "the", "and" }; 
    String parts = "the and of the"; 
    LinkedList<String> newWordList = new LinkedList<String>(
     Arrays.asList(parts.split(" "))); 

    for (Iterator<String> iter = newWordList.iterator(); iter.hasNext();) { 
     String word = iter.next(); 
     for (int i = 0; i < stopwords.length; i++) { 
      if (word.equals(stopwords[i])) { 
       iter.remove(); 
      } 
     } 
    } 
    System.out.println(newWordList.toString()); 
} 
+0

感謝您的回答,提出了您建議的更改,但我仍然獲得相同的輸出。也許在'for'循環中還有其他一些錯誤?以下鏈接包含測試程序[link](https://ideone.com/5tpR3d)。 –

+0

回覆我的回答... –

+0

完成回覆。請看看 –