import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet set = new HashSet();
Person p1 = new Person(1001, "AA");
Person p2 = new Person(1002, "BB");
set.add(p1);
set.add(p2);
System.out.println(set); //(1001, AA), (1002, BB)
p1.setName("CC");
set.remove(p1);
System.out.println(set); // (1002,BB),(1001,CC)
set.add(new Person(1001, "CC"));
System.out.println(set); // (1002,BB),(1001,CC),(1001,CC)
set.add(new Person(1001, "AA"));
System.out.println(set); //(1002,BB),(1001,CC),(1001,CC),(1001,AA)
}
}
class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
if (id != person.id) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
面试官:了解HashSet吗?请做下面的题目
最新推荐文章于 2024-11-09 20:55:41 发布
此篇博客展示了如何使用HashSet存储Person对象,并通过实例的添加、修改和删除操作,观察集合中元素的变化。重点讲解equals()和hashCode()方法在Person类中的实现,以及如何跟踪集合内容的更新。
摘要由CSDN通过智能技术生成