java - How to Sort a HashTable -
this question has answer here:
- how keep order of elements in hashtable 5 answers
may know why hashtable number not in order? after reach number. please, need expert. helps appreciated. alot!! code in jsp file.
<% vector vrow2 = new vector(); vector vfruit = new vector(); hashtable htitem = new hashtable(); vrow2.addelement("apple"); vrow2.addelement("banana"); vfruit.addelement(vrow2); htitem.put("1", vfruit); htitem.put("2", vfruit); htitem.put("3", vfruit); htitem.put("4", vfruit); htitem.put("5", vfruit); htitem.put("6", vfruit); // if htitem put 6 show correct order result 6,5,4,3,2,1 htitem.put("7", vfruit); // if htitem put 7 show incorrect order result 6,5,4,3,2,1,7 htitem.put("8", vfruit); // if htitem put 8 show result 6,5,4,3,2,1,8,7 htitem.put("9", vfruit); // if htitem put 9 show correct order 9,8,7,6,5,4,3,2,1 htitem.put("10", vfruit); // if htitem put 10 show incorrect order result 9,8,6,5,4,3,2,10,1 system.err.println("htitem==="+htitem); %>
output
htitem==={9=[[apple, banana]], 8=[[apple, banana]], 7=[[apple, banana]], 6=[[apple, banana]], 5=[[apple, banana]], 4=[[apple, banana]], 3=[[apple, banana]], 2=[[apple, banana]], 10=[[apple, banana]], 1=[[apple, banana]]}
expected output : 10,9,8,7,6,5,4,3,2,1
how make number of list in correct sequence every time htitem put new number.?
keys in hash table not ordered definition. order depends on key's hashcode().
if want have keys sorted use either linkedhashmap
guarantees keys retrieve in same order added or treemap
appropriate comparator
guarantees keys retrieved according comparator implementation.
since using contained number strings keys have implement comparator following:
public class numericstringcomparator() { public int compare(string s1, string s2) { return integer.parseint(s1) - integer.parseint(s2); } }
please note version not null
safe. welcome improve it.
Comments
Post a Comment