How to Eliminate Duplicate User Defined Objects As a Key in Java


In this example,we will learn how to avoid duplicate user defined objects as a key from LinkedHashMap.

Source Code

1)ForExample

package com.beginner.examples;

import java.util.LinkedHashMap;
import java.util.Set;
 
public class ForExample{
     
    private String name;
    private int number;
     
    public ForExample(String nm, int num){
        this.name = nm;
        this.number = num;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    
    public String toString(){
        return "name: " + name + "  number: " + number;
    }
    // implement equals() method at the user defined objects
    public boolean equals(Object obj){
        ForExample e = (ForExample) obj;
        return (e.name.equals(this.name) && e.number == this.number);
    }
    // implement hashcode() method at the user defined objects
    public int hashCode(){
        int hashcode = 0;
        hashcode = number*10;
        hashcode += name.hashCode();
        return hashcode;
    }
    
}

2)DuplicateKeyExample2

package com.beginner.examples;

import java.util.LinkedHashMap;
import java.util.Set;
 
public class DuplicateKeyExample {
 
    public static void main(String a[]){
         
        LinkedHashMap map = new LinkedHashMap();
        map.put(new ForExample("java", 110), "java");
        map.put(new ForExample("c++", 20), "c++");
        map.put(new ForExample("python", 75), "python");
        // print the map
        printMap(map);
        ForExample key = new ForExample("java", 110);
        map.put(key, "c");
        System.out.println("After adding dulicate key:");
        // print the map
        printMap(map);
    }
     
    public static void printMap(LinkedHashMap map){
         
        Set keys = map.keySet();
        for(ForExample p:keys){
            System.out.println(p + " -> " + map.get(p));
        }
    }
}

Output:

name: java  number: 110 -> java
name: c++  number: 20 -> c++
name: python  number: 75 -> python
After adding dulicate key:
name: java  number: 110 -> c
name: c++  number: 20 -> c++
name: python  number: 75 -> python

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments