Applying Custom Hashcode and LinkedHashSet for Object Storage in Java
Last Updated :
27 Feb, 2024
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;
class Person {
private int id;
private String name;
public Person( int id, String name) {
this .id = id;
this .name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + 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);
}
@Override
public int hashCode() {
return 31 * id + name.hashCode();
}
}
public class LinkedHashSetExample {
public static void main(String args[]) {
LinkedHashSet<Person> personSet = new LinkedHashSet<>();
Person person1 = new Person( 1 , "Sweta" );
Person person2 = new Person( 2 , "Gudly" );
personSet.add(person1);
personSet.add(person2);
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
import java.util.LinkedHashSet;
import java.util.ArrayList;
class Student {
private String name;
private int rollNo;
public Student(String name, int rollNo) {
this .name = name;
this .rollNo = rollNo;
}
@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;
}
@Override
public int hashCode() {
return 31 * rollNo + name.hashCode();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\ '' +
", rollNo=" + rollNo +
'}' ;
}
}
public class LinkedHashSetExample {
public static void main(String args[]) {
int [] rollNumbers = { 64 , 7 , 8 , 26 , 30 , 26 , 7 };
ArrayList<Integer> numList = new ArrayList<>();
for ( int num : rollNumbers) {
numList.add(num);
}
System.out.println( "Original list: " + numList);
LinkedHashSet<Integer> uniqueRollNumbers = new LinkedHashSet<>(numList);
System.out.println( "New list after removing duplicate numbers: " + uniqueRollNumbers);
LinkedHashSet<Student> studentSet = new LinkedHashSet<>();
studentSet.add( new Student( "Pooja" , 1 ));
studentSet.add( new Student( "Unnati" , 2 ));
studentSet.add( new Student( "Sweta" , 3 ));
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.
Share your thoughts in the comments
Please Login to comment...