Author
Need help for using Iterator
Ganesh Chandrasekaran
Greenhorn
Joined: Nov 14, 2000
Posts: 22
posted Feb 06, 2007 00:39:00
0
Hi, 1. I use the following code for HashMap , is it fine? ---------- HashMap hm = new HashMap (); hm.put("1","aaa"); hm.put("2","bbb"); hm.put("3","ccc"); hm.put("4","ddd"); hm.put("5","eee"); hm.put("6","fff"); hm.put("7","ggg"); hm.put("8","hhh"); hm.put("9","iii"); hm.put("10","jjj"); hm.put("11","kkk"); hm.put("12","lll"); hm.put("13","mmm"); hm.put("14","nnn"); hm.put("15","ooo"); Set st = hm.entrySet(); Iterator myIt = st.iterator(); while(myIt.hasNext()) { Map.Entry mapEntry = (Map.Entry)myIt.next(); System.out.println("==="+mapEntry.getKey()+" --- "+mapEntry.getValue()); } -------- the output i get is ===3 --- ccc ===7 --- ggg ===2 --- bbb ===14 --- nnn ===1 --- aaa ===6 --- fff ===10 --- jjj ===5 --- eee ===13 --- mmm ===15 --- ooo ===9 --- iii ===11 --- kkk ===4 --- ddd ===8 --- hhh ===12 --- lll which is in different order., but i want it in the same order as i have input. Please do help me in solving this problem. thanking in advance Ganesh
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12959
1. I use the following code for HashMap , is it fine? Yes, it's fine. About the order: Maps do not generally store elements in a predictable order, so it's not strange that the elements are listed in a different order than how you put them in the map. Use LinkedHashMap instead of HashMap if you want the elements to be listed in the order that you put them in the map.
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ganesh Chandrasekaran
Greenhorn
Joined: Nov 14, 2000
Posts: 22
posted Feb 06, 2007 04:36:00
0
Dear Jesper Young , Thank you very much for your suggestion, It is working as i wanted. thanks, Ganesh
subject: Need help for using Iterator