Question 1C What are the outputs of running class TestMap of
Question 1C What are the outputs of running class TestMap of the following code?
public class TestMap {
public static void main(String[] args) {
Map map = new LinkedHashMap<>();
map.put(\"123\", \"John Smith\");
map.put(\"111\", \"George Smith\");
map.put(\"123\", \"Steve Yao\");
map.put(\"222\", \"Steve Yao\");
System.out.println(\"(1) \" + map);
System.out.println(\"(2) \" + new TreeMap(map));
} }
Solution
There is a wrong in Above code line 3 . to correct it , write the argument type inside <>.
The corrected statement is
Map map = new LinkedHashMap<String,String>(); // as in subsequet lines ,map.put() takes two strings as <key,Value> pairs.
Now the output will be:-
System.out.println(\"(1) \" + map); outputs (1) {123=Steve Yao, 111=George Smith, 222=Steve Yao}
Explanation: enties in LinkedHashMap() are retrieve in ind order of insertion.
There are 4 put method, but as the key 123 is entried two times, the one key with 123 with new value=steve Yao will be entered. SO the keys are retrieved in order 123,111,222
System.out.println(\"(2) \"+ new TreeMap(map)); outputs- (2) {111=George Smith, 123=Steve Yao, 222=Steve Yao}
Explanation:Here aTreeMap object is used which abstracts map object. Entries are retrieved from A treeMap object in sorted orderby key.
![Question 1C What are the outputs of running class TestMap of the following code? public class TestMap { public static void main(String[] args) { Map map = new L Question 1C What are the outputs of running class TestMap of the following code? public class TestMap { public static void main(String[] args) { Map map = new L](/WebImages/1/question-1c-what-are-the-outputs-of-running-class-testmap-of-966754-1761495127-0.webp)