Question

public class random {

    public static class A{
        int id= 1;
        public int hashCode(){          
            return id;
        }
    }
    public static void main(String[] args) {
        Map<Integer, Integer> map= new HashMap<Integer, Integer>();
        A a = new A();
        A b = new A();
        map.put(a.id, 1);       
        map.put(b.id, 2);   

        System.out.println(map.get(a.id));
        System.out.println(map.get(b.id));
        System.out.println(map.size());
    }

}

output is

2
2
1

a and b have the same hashcode(bucket) and inside this bucket is (1 and 2). It says only one node exists which is b with the value of 2. When 2 hashcodes are the same do they override the current value? I read it is not the case.

from tutorial

*"Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. 

Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz2sCM7fNED*

does this mean that my map now has 1 bucket with 2 values? how do I grab the value of (1)

Was it helpful?

Solution 3

Both of them have the same id of "1", so when you add them to the map under the key of their id, they both get added with the key 1. So the second one overrides the first.

OTHER TIPS

You are using the Integer id as a key in the Map, not a or b. So the hashcode() of A is not used at all.

To get the values from a map, use the get method.

If you wanted to use a1 or a2 as the key, you would need to declare the map as such:

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

from the doc of hashmap of java (http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html)

HashMap.put()

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

So the new value will replace the old value.

You've made a bit of a mess.

A Map maps between keys and values. In your example, you're mapping integers to integers. First you're trying to map 1 to 1, then 1 to 2. A map can only map a key once - if you map the key a second time, it overwrites the first mapping.

Hash collisions happen when two different keys have the same hash value. If you created a Map<A, Integer> and mapped A and B to to some values, you would have had a collision, but would have gotten a map with two elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top