gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:34:44 26 4
gpt4 key购买 nike

对于此作业,我需要将每个包含 2 个字符串的自定义数据类(称为 User)的实例保存到 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 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();

关于java - TreeSet 上的迭代器导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com