I am trying to print the size of HashMap which contains key value pair at same bucket location. Following is the code. Please confirm the answer .
import java.util.HashMap; import java.util.Map;
public class HashcodeWork {
public static void main(String[] args) {
// int i = 34, j =15; // 2 and 18 34 -- bucket is 2 // int k = i & j ; // System.out.println(k); Map<Employee,String> map = new HashMap<Employee, String>(); Employee e1 = new Employee(2,"A"); Employee e3 = new Employee(18,"T"); Employee e5 = new Employee(34,"D"); map.put(e1, "A"); map.put(e3, "G"); map.put(e5, "O"); System.out.println(map + " Size:::: "+map.size());
}
}
class Employee { private Integer empId; private String name ;
public Employee(int i, String string) { // TODO Auto-generated constructor stub this.empId = i; this.name=string; } @Override public boolean equals(Object arg0) { // TODO Auto-generated method stub Employee e = (Employee) arg0; return this.empId.equals(e.empId); } @Override public int hashCode() { // TODO Auto-generated method stub int bucket = empId.hashCode(); System.out.println(bucket+" bucket "); return bucket; }
}
/* 2 bucket 18 bucket 34 bucket 2 bucket 18 bucket 34 bucket {com.pra.cg.Employee@2=A, com.pra.cg.Employee@12=G, com.pra.cg.Employee@22=O} Size:::: 3 */
Formula to calculate bucket location. // int i = 34, j =15; // 2 and 18 34 -- bucket is 2 // int k = i & j ; // System.out.println(k);
If this is not the way Java follows to calculate bucket location . I also tried with public int hashCode() { return 2; }
So whats the answer for , if bucket location is same for all the 3 elements then what will be the size of map?
Ads