java - java中Hashmap和ArrayList添加值的方式不同

标签 java arraylist hashmap

我想在 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).

这将使您的 MapList(由 ArrayList 支持)具有相同的元素顺序.

不确定您是如何设计您的应用程序的,但我建议您面向接口(interface)(MapList等)而不是类(HashMapArrayList等...)。更多信息:What does it mean to "program to an interface"?

关于java - java中Hashmap和ArrayList添加值的方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17017371/

相关文章:

java - 使用预定义的配置文件运行 Spring Boot JAR

java - IN 不工作的 JPA EntityManager createQuery()

java - 在 Java 中将 MySQL 数据库项存储在 ArrayList 中

java - 在Java中加载HashMap

java - 在java中对集合进行排序

javascript - 调试 Java Stream() NullPointerException 原因的最佳方法

java - 我的字典应该使用什么数据结构?

java - 连续子数组的最大和

java - 为什么这个 for 循环不起作用?

java - 获取 MP3 的标题会抛出 "java.lang.IllegalArgumentException"