Open In App

How to Create a LinkedHashSet with Custom Equality for Objects?

In this article, we want to create a LinkedHashSet of custom objects with specific equality criteria. So, we can create it by overriding the equals and hashcode methods in Java. In the equals() method, we can put the custom criteria over there and we override the hashcode to provide the same Hashcode to our custom object.

Example:

We want to implement a program that stores the information of students along with its insertion order. However the values must be unique, and the students cannot use the same identities.



Approach:

Program to Create a LinkedHashSet of Custom Objects with Specific Equality Criteria

Below is the code implementation of the creation of a LinkedHashSet of custom objects with specific equality criteria.




// Java Program to Create a LinkedHashSet of
// Custom Objects with Specific Equality Criteria
import java.io.*;
import java.util.LinkedHashSet;
import java.util.Objects;
  
// Driver Class
class GFG {
      // Main Function
    public static void main(String[] args)
    {
        // Create a LinkedHashSet
        LinkedHashSet<Student> StudentSet
            = new LinkedHashSet<>();
  
        // Add Students in the Set
        StudentSet.add(new Student(1, "Amit"));
        StudentSet.add(new Student(2, "Ankit"));
        StudentSet.add(new Student(3, "Abhishek"));
        StudentSet.add(new Student(1, "vikas"));
  
        // Printing the Output
        for (Student student : StudentSet)
            System.out.println("StudentID: " + student.getId()
                               + ", Name: "
                               + student.getName());
    }
}
  
// Custom Object Class
class Student {
    private int id;
    private String name;
  
    // Constructor
    public Student(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
  
    // Override equals method for custom criteria
    public boolean equals(Object o)
    {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        Student student = (Student)o;
        return id == student.id;
    }
  
    // Overriding hashCode method
    public int hashCode() {
      return Objects.hash(id); 
    }
  
    public int getId() {
      return id; 
    }
  
    public String getName() {
      return name; 
    }
}

Output

StudentID: 1, Name: Amit
StudentID: 2, Name: Ankit
StudentID: 3, Name: Abhishek


Explanation of the above Program:


Article Tags :