Problem statement:
Given java code as follows, can you find out the correct option to sort the keys in HashMap?
- import java.util.HashMap;
- import java.util.Set;
- import java.util.TreeSet;
- public class Test {
- public static void main(String[] args) {
- HashMap<String, String> m = new HashMap<String, String>();
- m.put("key45", "aa");
- m.put("key12", "bb");
- m.put("key39", "cc");
- Set<String> s = m.keySet();
- // code goes here
- s = new TreeSet(s);
- }
- }
- Arrays.sort(s);
- s = new TreeSet(s);
- Collections.sort(s);
- s = new SortedSet(s);
Correct option:
s = new TreeSet(s);
Explanation:
Arrays.sort(s) // sorts for static array
Collection.sort(s) // sort the List type of object not Set type
s =new SortedSet(s); // SortedSet is an interface
Explanation:
Arrays.sort(s) // sorts for static array
Collection.sort(s) // sort the List type of object not Set type
s =new SortedSet(s); // SortedSet is an interface
No comments:
Post a Comment