Java类实现Map并保持插入顺序? [英] Java Class that implements Map and keeps insertion order?

查看:162
本文介绍了Java类实现Map并保持插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个具有键值关联但不使用哈希值的java中的类。这是我目前正在做的:

I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:


  1. 将值添加到 Hashtable 中。

  2. 获取 Hashtable.entrySet()的迭代器。

  3. 通过所有值迭代和

  1. Add values to a Hashtable.
  2. Get an iterator for the Hashtable.entrySet().
  3. Iterate through all values and:

  1. 为迭代器获取一个 Map.Entry

  2. 根据该值创建一个类型为 Module (一个自定义类)的对象。

  3. 将类添加到JPanel。

  1. Get a Map.Entry for the iterator.
  2. Create an object of type Module (a custom class) based on the value.
  3. Add the class to a JPanel.


  • 显示面板

  • 这个问题是我无法控制我的值,所以我不能显示给定的顺序的值(没有硬编码的顺序)。

    The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).

    我将使用 ArrayList Vector ,但后来我需要的代码获取给定密钥的模块对象,我不能使用 ArrayList 矢量

    I would use an ArrayList or Vector for this, but later in the code I need to grab the Module object for a given Key, which I can't do with an ArrayList or Vector.

    有谁知道一个免费/开源Java c这样做的懒惰,或者是根据添加时间,从 Hashtable 中获取价值的方法。

    Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable based on when they were added?

    谢谢!

    推荐答案

    我建议一个 LinkedHashMap TreeMap LinkedHashMap 按照插入的顺序保存键,而 TreeMap 通过比较器或元素的自然可比较顺序。

    I suggest a LinkedHashMap or a TreeMap. A LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the elements.

    既然它没有在大多数情况下,不得不保持元素的排序, LinkedHashMap 应该更快; TreeMap 具有 O(log n)表现为 containsKey 根据Javadocs,获取 put 删除 ,而 LinkedHashMap O(1)

    Since it doesn't have to keep the elements sorted, LinkedHashMap should be faster for most cases; TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each.

    如果您的API只能预期可排序的排序顺序,而不是特定的排序顺序,请考虑使用这两个类实现的接口, NavigableMap SortedMap 。这将允许您不要将特定的实现泄漏到您的API中,并可以随时切换到任何一个特定类或完全不同的实现。

    If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap or SortedMap. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.

    这篇关于Java类实现Map并保持插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆