如何遍历LinkedList并从Java中删除某些单词
试图从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();
}
}
}
当你比较字符串,你需要使用.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());
}
感谢您的回答,提出了您建议的更改,但我仍然获得相同的输出。也许在'for'循环中还有其他一些错误?以下链接包含测试程序[link](https://ideone.com/5tpR3d)。 –
回复我的回答... –
完成回复。请看看 –
,如果你想,如果你想删除重复使用'Set' **'iterate' **和删除使用'Iterator'但首先决定你的操作 – emotionlessbananas
@FlyingZombie感谢您的评论。我想保留重复的内容,这就是为什么我不使用'Set'。 –
虽然最初这个问题似乎是关于字符串比较,但在更仔细的检查中,它也是关于字符串分割/集合初始化。 –