Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

Monday, September 7, 2026

Understanding hashCode() in Java


Understanding hashCode() in Java

The hashCode() method is defined in the Object class and is used to return a hash code value for an object.

It is especially important when working with hash-based collections such as HashMap, HashSet, and Hashtable.

public int hashCode()


General contract of hashCode()

There are a few important rules that should be followed:

If hashCode() is called multiple times on the same object during a Java application execution, it should return the same integer value as long as the information used by equals() has not changed.

If two objects are considered equal according to the equals() method, they must return the same hash code. Two objects that are not equal do not have to return different hash codes. Different objects can have the same hash code. This is called a hash collision.

Having fewer collisions can improve the performance of hash-based collections.

Example

Consider the following class:

public class Employee {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Employee)) {
            return false;
        }

        Employee employee = (Employee) obj;

        return id == employee.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

Here, id is used to determine whether two Employee objects are equal. Therefore, the same id is also used to calculate the hash code.

This is important because:

Employee e1 = new Employee(101, "John");
Employee e2 = new Employee(101, "David");
System.out.println(e1.equals(e2)); // true 
System.out.println(e1.hashCode());
System.out.println(e2.hashCode());



Since both objects have the same id, they are considered equal and must have the same hash code.


Why is hashCode() important?

Hash-based collections use the hash code to efficiently locate objects.


For example:

HashSet<Employee> employees = new HashSet<>(); 

employees.add(new Employee(101, "John"));

employees.add(new Employee(101, "David"));

System.out.println(employees.size());


Because the two objects are considered equal based on id, the HashSet treats them as the same element.


Important point

  1. If you override equals(), you should also override hashCode().
  2. The basic rule to remember is:
  3. If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
  4. However, the reverse is not required:
  5. Same hash code does not mean that two objects are equal.

Thursday, July 11, 2019

Find Duplicate Values in a List Using Java

In this article, we will see how to find the duplicate values from an array or list using java.  This is one of important programming questions in technical interview. Each interviewer has different approach to access the candidate. But, the logic and the approach by candidate is really matter. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see how to find the duplicate values from array. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).


DuplicateFinder.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicateFinder {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>(
                Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90));

        System.out.println("Input List Data = " + list);

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < list.size(); i++) {

            if (map.isEmpty()) {
                map.put(list.get(i), 1);
            } else if (map.containsKey(list.get(i))) {
                map.put(list.get(i), map.get(list.get(i)) + 1);
            } else {
                map.put(list.get(i), 1);
            }
        }

        System.out.println("\nDuplicate values are: ");

        // Iterate the Map and display the duplicate values.
        for (Entry<Integer, Integer> entry : map.entrySet()) {

            if (entry.getValue() > 1) {
                System.out.println(entry.getKey());

                // TODO: We can now put these values into any list.
            }
        }
    }
}

Output:

Input List Data = [4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90]

Duplicate values are:
4
5
25

Note- One small point: because HashMap does not guarantee iteration order, the order of 4, 5, and 25 in the output can vary.



Happy Learning.