簡體   English   中英

TreeSet上的迭代器導致無限循環

[英]Iterator over TreeSet causes infinite loop

對於此分配,我需要將每個包含2個字符串的自定義數據類(稱為User)的實例保存到TreeSet中。 然后,我必須在我創建的TreeSet中搜索從另一個文件的每一行獲取的字符串。 第一個文件是.csv文件,其中每行包含一個電子郵件地址和一個名稱,.txt文件僅包含地址。 我必須搜索.txt文件中的每一行,並且還必須將整個操作重復4000次。

我無法使用.contains搜索TreeSet,因為無法按用戶搜索,因為.txt文件僅包含User所做的兩條信息之一。 根據在不同地方找到的信息,我可以從TreeSet中獲取迭代器,並使用它來檢索其中的每個User,然后獲取User的用戶名並將其直接與第二個文件中的字符串進行比較。 我完全按照發現的每個站點的建議編寫了代碼,但是我的程序仍然陷入無限循環。 這是我到目前為止的搜索代碼:

for (int i = 0; i < 4000; i++)//repeats search operation 4000 times
{
  try
  {
    BufferedReader fromPasswords = new BufferedReader(new FileReader("passwordInput.txt"));

    while ((line = fromPasswords.readLine()) != null)
    {
      Iterator it = a.iterator();
      while (it.hasNext())
      {
        //the infinite loop happens about here, if I put a println statement here it prints over and over
        if(it.next().userName.compareTo(line) == 0)
          matches++; //this is an int that is supposed to go up by 1 every time a match is found
      }
    }
  }
  catch (Exception e)
  {
    System.out.println("Error while searching TreeSet: " + e);
    System.exit(0);
  }
}

有關其他信息,這是我的User類。

class User implements Comparable<User>
{
  String userName;
  String password;

  public User() { userName = "none"; password = "none"; }
  public User(String un, String ps) { userName = un; password = ps; } 

  public int compareTo(User u)
  {
    return userName.compareToIgnoreCase(u.userName);
  }
} //User

我似乎正確地完成了所有操作,但是在我看來,即使當我調用next()時,迭代器也不會移動其指針。 有人看到我想念的東西嗎?

編輯:感謝KevinO指出這一點-a是TreeSet的名稱。

編輯:這是TreeSet的聲明。

TreeSet<User> a = new TreeSet<User>();

您確定存在無限循環嗎? 您將打開一個文件4000次,並對文件中的每一行進行遍歷一個集合。 根據文件和集合的大小,這可能需要很長時間。

需要注意的其他事項:

  • 更高版本的Java具有更簡潔的方式來打開文件並遍歷所有行: Files.lines
  • 您不需要Iterator即可迭代集合。 普通的for-each循環會執行或將其轉換為流
  • 如果您要做的只是計算比賽數,那么串流同樣出色

將所有內容放在一起:

Path path = Paths.get("passwordInput.txt");
Set<User> users = new TreeSet<>();

long matches = Paths.lines(path)
    .mapToLong(l -> users.stream()
        .map(User::getName).filter(l::equals).count())
    .sum();

暫無
暫無

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

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