我想在 arraylist 和 hashmap 中添加值。当我添加值时,我注意到映射在前面添加值并在最后列出添加值。但我希望两者都以一种方式添加。如何做那个。
我要添加到 HashMap 中的值是 4055,5040 在我的列表中 20,37
但是添加列表时给出了预期的结果,但 map 给出的输出为 5040,4055。
最佳答案
使用LinkedHashMap
而不是HashMap
。前者保留元素插入的顺序。
来自其 JavaDoc(强调我的):
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
这将使您的 Map
和 List
(由 ArrayList
支持)具有相同的元素顺序.
不确定您是如何设计您的应用程序的,但我建议您面向接口(interface)(Map
、List
等)而不是类(HashMap
、ArrayList
等...)。更多信息:What does it mean to "program to an interface"?
关于java - java中Hashmap和ArrayList添加值的方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17017371/