Open In App

Applying Custom Hashcode and LinkedHashSet for Object Storage in Java

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The LinkedHashSet is an ordered version of HashSet that maintains a doubly linked list across all elements. Unlike a regular HashSet, which has unpredictable iteration order, a LinkedHashSet allows us to iterate through elements in the order they were inserted. It’s useful when maintaining insertion order.

In this article, we will learn how to use LinkedHashSet with custom objects and custom hashcode implementations in Java.

Steps to Create and Use a LinkedHashSet with Custom Objects and Custom Hashcode

To create and use a LinkedHashSet with Custom objects, follow these steps:

Step 1: Define the Custom class

  • Create a custom class (e.g., MycustomObject ) to store in the LinkedHashSet.
  • Implement the necessary methods such as equals( ) and hashCode( ) for custom class.

Step 2: Create a LinkedHashSet

LinkedHashSet <MyCustomObject> customSet = new LinkedHashSet <>();

Step 3: Add Custom Objects

MyCustomObject obj1  =  new MyCustomObject(/* initialize with relevant data */);
MyCustomObject obj12 = new MyCustomObject(/* initialize with relevant data */);
customSet.add( obj1 );
customSet.add( obj2 );

Step 4: Iterate Through the LinkedHashSet

for (MyCustomObject obj : customSet) {
// Process each custom object
}

Parameters and Return Value

Below are the Parameters and Return Values.

Parameters:

  • MyCustomObject: Represents custom class
  • obj1, obj2, etc: Instances of custom class

Return Value:

  • None (since it’s a data Structure)

Approaches:

  • Ensure that the custom class (MyCustomObject) override the equals() and hashCode() methods.
  • Use the LinkedHashSet to Store Instance of the custom class.

Program to Use LinkedHashSet With Custom Objects and Custom Hashcode

Example 1: Let’s create a simple example using a Person class.

Java




import java.util.LinkedHashSet;
  
// Person class representing 
// A person with an id and name
class Person {
    private int id;
    private String name;
  
    // Constructor to initialize id and name
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
  
    // Overriding toString method to print
      // The id and name of a person
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
  
    // Implementing equals method to check if
      // Two persons are equal based on id and name
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Person other = (Person) obj;
        return id == other.id && name.equals(other.name);
    }
  
    // Implementing hashCode method to generate a
      // Unique hash code for each person object
    @Override
    public int hashCode() {
        return 31 * id + name.hashCode();
    }
}
  
public class LinkedHashSetExample {
    public static void main(String args[]) {
        // Create a LinkedHashSet of custom objects (Person)
        LinkedHashSet<Person> personSet = new LinkedHashSet<>();
  
        // Creating two Person objects
        Person person1 = new Person(1, "Sweta");
        Person person2 = new Person(2, "Gudly");
  
        // Adding the Person objects to the LinkedHashSet
        personSet.add(person1);
        personSet.add(person2);
  
        // Printing the size and the original LinkedHashSet
        System.out.println("Size of LinkedHashSet: " + personSet.size());
        System.out.println("Original LinkedHashSet: " + personSet);
    }
}


Output

Size of LinkedHashSet: 2
Original LinkedHashSet: [Person{id=1, name='Sweta'}, Person{id=2, name='Gudly'}]

Explanation of the above Program:

  • We have used a LinkedHashSet named personSet to store Person objects.
  • Two Person objects are added to the set.
  • The LinkedHashSet maintains the order in which elements were added.
  • And the objects are printed in that order.
  • At last, it prints the size of the set and its contents.

Example 2:

In this example, we will create a Student class and then we will implement how to add elements to the set, remove duplicates, and perform other operations.

Java




// Java Program to 
import java.util.LinkedHashSet;
import java.util.ArrayList;
  
// Student class representing a student
// with a name and roll number
class Student {
    private String name;
    private int rollNo;
  
    // Constructor to initialize name and roll number
    public Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }
  
    // Overriding equals method to check if two students
      // Are equal based on name and roll number
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Student other = (Student) obj;
        return name.equals(other.name) && rollNo == other.rollNo;
    }
  
    // Overriding hashCode method to generate a unique
      // Hash Code for each student object
    @Override
    public int hashCode() {
        return 31 * rollNo + name.hashCode();
    }
  
    // Overriding toString method to print
      // The name and roll number of a student
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", rollNo=" + rollNo +
                '}';
    }
}
  
public class LinkedHashSetExample {
    public static void main(String args[]) {
        // Array of roll numbers
        int[] rollNumbers = {64, 7, 8, 26, 30, 26, 7};
        ArrayList<Integer> numList = new ArrayList<>();
  
        // Adding numbers to the ArrayList
        for (int num : rollNumbers) {
            numList.add(num);
        }
  
        // Printing the original list
        System.out.println("Original list: " + numList);
  
        // Create a LinkedHashSet to remove duplicate numbers
        LinkedHashSet<Integer> uniqueRollNumbers = new LinkedHashSet<>(numList);
  
        // Printing the new list after removing duplicate numbers
        System.out.println("New list after removing duplicate numbers: " + uniqueRollNumbers);
  
        // Create a LinkedHashSet of custom objects (Student)
        LinkedHashSet<Student> studentSet = new LinkedHashSet<>();
        studentSet.add(new Student("Pooja", 1));
        studentSet.add(new Student("Unnati", 2));
        studentSet.add(new Student("Sweta", 3));
  
        // Printing the student set
        System.out.println("Student set: " + studentSet);
    }
}


Output

Original list: [64, 7, 8, 26, 30, 26, 7]
New list after removing duplicate numbers: [64, 7, 8, 26, 30]
Student set: [Student{name='Pooja', rollNo=1}, Student{name='Unnati', rollNo=2}, Student{name='Sw...

Explanation of the above Program:

  • We have defined a Student class with name and rollNo fileds.
  • Then we have created an ArrayList to store roll numbers (including duplicates).
  • After that we use a LinkedHashSet to remove duplicate roll numbers.
  • At last, we create a LinkedHashSet of Student objects and print the results.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads