简体   繁体   中英

Trying to compare each element of two different ArrayLists

So I need to compare two different ArrayLists elements. 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)

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. 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.

You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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