Saturday, August 28, 2010

Output of equals() depends on how the hashing function is implemented

Courtesy of Sun Web Learning Center

Given:

1. import java.util.*;
2. class DumpMap {
3.   public static void main(String [] args) {
4.     HashMap h = new HashMap();
5.     h.put("a","aa"); h.put("b","bb"); h.put("c","cc");
6.     Set ks = h.keySet();
7.     Object [] ka1 = ks.toArray();
8.     ks = new TreeSet(ks);
9.     Object [] ka2 = ks.toArray();
10.     System.out.println(Arrays.equals(ka1, ka2));
11.   }
12. }
What is the result?


A true
B false
C Compilation fails due to an error on line 8.
D The output depends on how the hashing function is implemented.

D is correct. ka2 is sorted, but there is no guarantee what order ka1's elements are in.

No comments:

Post a Comment