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)
a.id == b.idso it overwrites the previous entry.Integer.valueOf(1)).1). This has nothing to do with the hashcode of your object.