简体   繁体   English

试图比较两个不同ArrayLists的每个元素

[英]Trying to compare each element of two different ArrayLists

So I need to compare two different ArrayLists elements. 所以我需要比较两个不同的ArrayLists元素。 If the element from the first ArrayList(tweets) does not match any from the second(hashTags) I want to add the element(from tweets) to the second ArrayList(hashTags) 如果第一个ArrayList(tweets)中的元素不匹配第二个(hashTags)中的元素,我想将元素(来自tweets)添加到第二个ArrayList(hashTags)

Here is my code thus far: 到目前为止,这是我的代码:

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));

    }
}

(edit)I seem to get a 'java.util.ConcurrentModificationException' error. (编辑)我似乎收到'java.util.ConcurrentModificationException'错误。 Thank you for any and all help:) 感谢您提供的所有帮助:)

    for (String hashTagged : hashTags) {
                        if (tweet.equalsIgnoreCase(hashTagged) != true) {
                            hashTags.add(hashTagged);
  -----------------------------^
                        }
                    }

The issue is while iterating the hashTags list you cant update it. 问题是在迭代hashTags列表时,您无法更新它。

You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it. 之所以得到java.util.ConcurrentModificationException是因为您在遍历List hashTags时对其进行了修改。

for (String hashTagged : hashTags) {
    if (tweet.equalsIgnoreCase(hashTagged) != true) {
        hashTags.add(hashTagged);
    }
}

You can create a temporary list of items that must be removed or improve your logic. 您可以创建必须删除的项目的临时列表,也可以改善逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM