import java.util.*;

class Data
{
    int num;
    String name;
    Data(String na)
    {
        name=na;
    }

    public int hashCode()
    {
        return 5;
    }

    public boolean equals(Object o)
    {
        if(o instanceof Data && ((Data)o).name==this.name) 
            return true;
        else
            return false;
    }
}
public class Sandeep {

    public static void main(String[] args)
    {
        HashMap map=new HashMap();
        Data d1=new Data("Aditya");
        Data d2=new Data("Aditya");
        map.put(d1,"abc");
        map.put(d2,"abcd");

        System.out.println(map.get(d1));
        System.out.println(map.get(d2));
        System.out.println(map.size());
        System.out.println(d1 + " " +d2);




    }

}

O/Pl;
abcd
1
Data@5 Data@5

I have two duplicate objects. When i put these two objects in a hashmap only one of the object is going to d map(i.e.d2) but when i try to get the value corresponding to d1 key i get the value that of d2. Can you explain why??

Try to read what the hashCode method really does and what it is used for.
Check the API of the Object class, as well as the API of the HashMap.

Also don't use '==' to compare Strings. Use the equals method of the String class. And you also need to check, in the equals method that o and name are not null, before calling any method on them.
The d1, d2 will not be equal with the way you have defined the equals method.

See the mechanism, how HashMap stores key value pair internally, then it will be clear to you.
When an object is put in a HashMap,it uses hashCode of the object to decide the location where the value will be stored. Also it maintains an array of keys based on hashcodes.
Now if you want to put another object in the HashMap, it first checks the hashcode of the key and try to store the key in proper location. Now in proper location, if it finds that already some key is stored, it compare the new key with the already stored key using the equals() method. If it returns true, then it does not store the new key, instead override the value of the already stored key with the new value, as to the hashmap, both the keys are same.

In your case, your hashmap always returns a constant, hence for all object the hashcode is same. Hence, when you add the second object in the hashmap i.e.

Data d2=new Data("Aditya");
map.put(d2,"abcd");

it just overrides the value against the already stored key as the two objects are same to the hashmao according to hashcode() and equals() method.
Also, you will find that the size of the hashmap is 1 as the second object is not stored in the map, it just overrides the value against the first object.

Hope that the problem is clear to you now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.