Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections

 
deshdeep divakar
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?

import java.util.*;
public class Thirsk{
public static void main(String argv[]){
Thirsk t = new Thirsk();
t.a19();
}
public void a19(){
TreeMap tm = new TreeMap();
tm.put("a","Bill");
tm.put("b","Kathy");
tm.put("c","Carl");
Iterator it = tm.keySet().iterator();
while(it.hasNext()){
System.out.print(tm.get(it.next()));
}
}
}



1) Compile time error, a19 cannot be used as a method name
2) Compilation and output of BillKathyCarl
3) Compilation and output of BillCarlKathy
4) Compilation and output of abc

Ans according to me have to be option 2,but the correct answer is becoz
put(Object Key, Object Value)//Associates the specified value with the specified key in this map

get(Object Key)//Returns the value to which this map maps the specified key
plz guide where I went wrong.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is 2. Run the code yourself.

A TreeMap stores the keys in a tree in sorted order, which defaulkts to alphabetical order. Therefore, the iterator retrieves "a" "b" "c" in that order. These keys retrieve the corresponding objects "Bill" "Kathy" "Carl" in that order.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic