Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HashSet Java示例_Java_Hashset - Fatal编程技术网

HashSet 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;

在Java中,我有这样一个集合:

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发布你的评论,作为有趣、投票和接受的答案!