I have a hashtable, which contains strings for example, when I use put method as below
hashtable.put("1","A");
hashtable.put("1","B");
hashtable.put("1","C");
hashtable.put("1","D");
hashtable.put("1","E");
Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?
Collection c = ht.values();
Iterator itr = c.iterator();
while(itr.hasNext())
System.out.println(itr.next());
Thanks Max
A Hashtable
does not guarantee any kind of ordering.
If you want to preserve insertion order, use a LinkedHashMap
. However, the contract is slightly different than a Hashtable
in that it allows null elements.
如果要按顺序打印项目,则应使用LinkedHashMap 。
That is simply the property of a hash table -- it makes no guarantee about ordering. Do you want to use a LinkedHashMap instead?
HashTable不会保持顺序,它将随机打印,您应该使用LinkedHashMap。您可以像使用HashMap一样使用LinkedHashMap。只需将LinkedHashMap替换为HashMap.LinkedHashMap会保持输入数据的顺序。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.