所以我需要比较两个不同的 ArrayLists 元素。如果第一个 ArrayList(tweets) 中的元素与第二个 ArrayList(hashTags) 中的任何元素都不匹配,我想将该元素(来自 tweets)添加到第二个 ArrayList(hashTags)
这是迄今为止我的代码:
package edu.bsu.cs121.albeaver;
import java.util.*;
public class HashTagCounter {
public static void main(String args[]) {
System.out
.println("Please tweet your tweets,and type 'done' when you are done.");
Scanner twitterInput = new Scanner(System.in);
ArrayList<String> tweets = new ArrayList<String>();
ArrayList<String> hashTags = new ArrayList<String>();
while (true) {
String tweet = twitterInput.next();
tweets.add(tweet);
if ("done".equals(tweet))
break;
}
System.out.println(tweets);
twitterInput.close();
int count = 0;
for (String tweet : tweets) {
if (tweet.contains("#") && count == 0) {
hashTags.add(tweet);
hashTags.add(1, "");
count++;
} else if (tweet.contains("#")) {
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
}
}
System.out.println(hashTags);
System.out.println("Number of unique '#' used is: "
+ (hashTags.size() - 1));
}
}
(编辑)我似乎收到“java.util.ConcurrentModificationException”错误。 感谢您提供的所有帮助:)
最佳答案
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
-----------------------------^
}
}
问题是在迭代 hashTags 列表时您无法更新它。
关于java - 尝试比较两个不同 ArrayList 的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957216/