I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:
- Add values to a Hashtable
- Get an iterator for the Hashtable.entrySet().
- Iterate through all values and:
- Get a Map.Entry for the iterator
- Create an object of type Module (a custom class) based on the value.
- Add the class to a JPanel;
- Show the panel.
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).
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.
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?
I suggest a
LinkedHashMap or 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.
Since it doesn't have to keep the elements sorted,
LinkedHashMap should be faster for most cases;
O(log n) performance for
remove, according to the Javadocs, while
O(1) for each.
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,
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.
If an immutable map fits your needs then there is a library by google called guava (see also guava questions)
Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.
ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.
You can maintain a Map (for fast lookup) and List (for order) but a LinkedHashMap may be the simplest. You can also try a SortedMap e.g. TreeMap, which an have any order you specify.
I don't know if it is opensource, but after a little googling, I found this implementation of Map using ArrayList. It seems to be pre-1.5 Java, so you might want to genericize it, which should be easy. Note that this implementation has O(N) access, but this shouldn't be a problem if you don't add hundreds of widgets to your JPanel, which you shouldn't anyway.
You could try my Linked Tree Map implementation.
Put your values in a Map and use a key which wraps your Module object which then properly implements equals and hashCode.