📜  如何从Java中的 LinkedHashSet 中消除重复的用户定义对象?

📅  最后修改于: 2022-05-13 01:55:25.381000             🧑  作者: Mango

如何从Java中的 LinkedHashSet 中消除重复的用户定义对象?

创建HashSet 自己的类,始终确保HashSet的key的HashCode()方法不会改变。 Java Object hashCode()是一个本机方法,它返回对象的整数哈希码值。如果根据 equals() 方法两个对象相等,则它们的哈希码必须相同。如果根据 equals() 方法两个对象不相等,则它们的哈希码不需要不同。

句法:

equals() 方法:

public boolean equals  (Object obj)

// This method checks if some other Object
// passed to it as an argument is equal to 
// the Object on which it is invoked.

HashCode() 方法:

public int hashCode()

// This method returns the hash code value 
// for the object on which this method is invoked.

在Java应用程序的执行过程中,只要在同一对象上多次调用它(散列码)hashCode方法必须始终返回相同的整数,前提是对象上的 equals 比较中使用的信息没有被修改。

如果根据equals(Object)方法两个对象相等,则对两个对象中的每一个调用hashCode()方法必须产生相同的整数结果。

下面是上述问题陈述的实现:

Java
// Java Program  to eliminate duplicate user 
// defined Objects from LinkedHashSet
import java.util.*;
// Java program to illustrate
// overriding of equals and
// hashcode methods
class student {
    int marks;
    String name;
    // Constructor
    public student(String name, int marks)
    {
        this.marks = marks;
        this.name = name;
    }
    // Getters and Setters
    public int getMarks() { return marks; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public void setMarks(int marks) { this.marks = marks; }
    @Override public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + marks;
        result = prime * result
                 + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    // if both the object references are
    // referring to the same object.
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
  
        // type casting of the argument.
        student other = (student)obj;
  
        // comparing the state of argument with
        // the state of 'this' Object
        if (marks != other.marks)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        }
        else if (!name.equals(other.name))
            return false;
        return true;
    }
}
  
public class GFG {
  
    public static void main(String[] args)
    {
        // HashSet initialization
        HashSet set = new HashSet<>();
  
        // Add entries in HashSet
        set.add(new student("sam", 452));
        set.add(new student("cam", 451));
        set.add(new student("sam", 452));
        set.add(new student("cam", 451));
        for (student std : set) {
            System.out.println(std.name + " " + std.marks);
        }
    }
}


输出
cam 451
sam 452