How to Avoid Duplicate User Defined Objects As a Key from HashMap in Java


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

Source Code

1)ForExample

package com.beginner.examples;

import java.util.HashMap;
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)DuplicateKeyExample

package com.beginner.examples;

import java.util.HashMap;
import java.util.Set;
 
public class DuplicateKeyExample {
 
    public static void main(String a[]){
         
        HashMap map = new HashMap();
        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(HashMap map){
         
        Set keys = map.keySet();
        for(ForExample p:keys){
            System.out.println(p + " -> " + map.get(p));
        }
    }
}

Output:

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

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments