TreeSet 上的迭代器导致无限循环

Iterator over TreeSet causes infinite loop

对于此作业,我需要将每个包含 2 个字符串的自定义数据实例 class(称为用户)保存到 TreeSet 中。然后,我必须在我创建的 TreeSet 中搜索从另一个文件的每一行中提取的字符串。第一个文件是 .csv 文件,其中每一行包含一个电子邮件地址和一个名称,.txt 文件仅包含地址。我必须在.txt文件中搜索每一行,而且我还必须重复整个操作4000次。

我无法使用 .contains 搜索 TreeSet,因为我无法按用户搜索,因为 .txt 文件仅包含用户搜索的两条信息之一。根据我在不同地方找到的信息,我可以从我的 TreeSet 中获取迭代器并使用它来检索其中的每个用户,然后获取用户的用户名并将其直接与来自第二个文件的字符串。我完全按照我发现的每个网站的建议编写代码,但我的程序仍然陷入无限循环。这是我目前的搜索代码:

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

有关其他信息,这是我的用户 class。

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