HashSet Java示例
在Java中,我有这样一个集合:HashSet Java示例,java,hashset,Java,Hashset,在Java中,我有这样一个集合: Set<Student> studentsSet = new HashSet<Student>(); Set studentsSet=new HashSet(); 有人能举例说明如何在示例中使用此功能吗?阐述我刚才提到的注释: 使用rollNumber作为标识,以实现equals()和hashcode()方法。例如,Student类可以如下所示: class Student { private int rollNumber;
Set<Student> studentsSet = new HashSet<Student>();
Set studentsSet=new HashSet();
有人能举例说明如何在示例中使用此功能吗?阐述我刚才提到的注释: 使用
rollNumber
作为标识,以实现equals()
和hashcode()
方法。例如,Student
类可以如下所示:
class Student {
private int rollNumber;
private String name;
public Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
@Override
public int hashCode() {
return rollNumber;
}
@Override
public boolean equals(Object obj) {
Student other = (Student) obj;
return (rollNumber == other.rollNumber);
}
}
您可以通过这种方式删除学生-请注意,只有卷号才会影响从集合中删除的内容,这与等于和hashcode
查找的内容一致:
Set<Student> students = new HashSet<Student>();
students.remove(new Student(3, "I don't care what her/his name is!"));
Set students=newhashset();
移除(新学生(3,“我不在乎她/他的名字是什么!”);
您的集合是否由学生对象组成?若有,;使用卷号作为标识,重写Student类的equals()和hashcode()方法。现在只需说studentsSet.remove(newstudent(3))@aquaraga发布你的评论,作为有趣、投票和接受的答案!