我有一个
Set tablica = new HashSet();
我想搜索它,所以我写了这样的东西:
public void searchStudentbySurname() {
int a = tablica.size();
if (0 >= a) {
JOptionPane.showMessageDialog(null, "No data");
} else {
String S = JOptionPane.showInputDialog(null, "Give me a surname");
Iterator itr = tablica.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
if(tablica.equals(S)) { // this if doesn't work (1)
JOptionPane.showMessageDialog(null, str);
}
}
}
}
}
我想知道为什么 (1) 不起作用。
最佳答案
您正在将字符串与集合进行比较,因此它无法返回 true。
您可能想将其与 str
- str.equals(S)
进行比较,但即使这样也没有必要。
您只需用 tablica.contains(S)
替换整个 while 循环即可。这就是Set
的用途。
关于java - 在 Hashcode 中搜索在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26905433/