簡體   English   中英

試圖比較兩個不同ArrayLists的每個元素

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

所以我需要比較兩個不同的ArrayLists元素。 如果第一個ArrayList(tweets)中的元素不匹配第二個(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.util.ConcurrentModificationException是因為您在遍歷List hashTags時對其進行了修改。

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

您可以創建必須刪除的項目的臨時列表,也可以改善邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM