如何解决从HashSet中删除一个元素
我想从HashSet中删除一个元素。 sb可以帮助我理解为什么为什么不能从此HashSet中删除cat“ emma”吗? 最好的解决方案是什么?
谢谢!
public static void main(String[] args) {
HashSet<Cat> set = new HashSet<Cat>();
set.add(new Cat("cindy"));
set.add(new Cat("emma"));
Iterator<Cat> iterator = set.iterator();
while (iterator.hasNext()) {
Cat name1 = iterator.next();
if (name1.equals("emma")) {
iterator.remove();
}
}
System.out.println(set);
}
public static class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
解决方法
您正在使用Cat的equals
方法,并将字符串作为参数,该方法返回false。您可以使用toString
方法来覆盖它,也可以使用getter
作为名称并将其与字符串进行比较。
boolean equals(Object anObject)
请注意,equals
方法接受Objects
,因此当两个变量不是您期望的String
时,您不会得到异常(顺便说一句,IntelliJ IDEA为您提供了检查这种情况)。您需要解决的所有问题就是将String "emma"
与name1.name
进行比较:
while (it.hasNext()) {
Cat name1 = it.next();
if ("emma".equals(name1.toString()))
it.remove();
}
,
运行以下代码可以看到您的问题:
Cat c = new Cat("emma");
if(c.equals("emma"))
System.out.println("true"); // this is what you expect
else
System.out.println("false!"); // this is what actually happens!
这是因为,如果未定义equals
方法,则默认情况下它将比较两个对象完全相同。您可以找到有关此行为here和here的更多信息。在您的情况下,您正在将String
对象与Cat
对象进行比较。
一种可能的解决方案是使用您在类中定义的toString
方法在字符串之间进行比较。 equals
类中的String
方法被重写以具有您期望的行为。
public static void main(String[] args) {
HashSet<Cat> set = new HashSet<Cat>();
set.add(new Cat("cindy"));
set.add(new Cat("emma"));
Iterator<Cat> iterator = set.iterator();
while (iterator.hasNext()) {
Cat name1 = iterator.next();
if (name1.toString().equals("emma")) {
iterator.remove();
}
}
System.out.println(set);
}
另一种解决方案可能是覆盖cat类中的equals
方法。这是您可以执行的一种方法:
import java.util.*;
class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
public Boolean equals(Cat other) {
return this.name.equals(other.name);
}
}
public class Test {
public static void main(String[] args) {
HashSet<Cat> set = new HashSet<Cat>();
Cat cindy = new Cat("cindy");
Cat emma = new Cat("emma");
set.add(cindy);
set.add(emma);
Iterator<Cat> iterator = set.iterator();
while (iterator.hasNext()) {
Cat cat = iterator.next();
if (cat.equals(emma)) {
iterator.remove();
}
}
System.out.println(set);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。