views:

1574

answers:

6

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. Add values to a Hashtable
  2. Get an iterator for the Hashtable.entrySet().
  3. Iterate through all values and:
    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;
  4. 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?

Thanks!

+20  A: 

Try using a LinkedHashMap, which keeps the keys in the order they were inserted.

EDIT: Or a TreeMap, which you can actually sort. But LinkedHashMap should be faster for most cases (TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs).

Michael Myers
This answer looks much uglier now that inline code has a gray background.
Michael Myers
A: 

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.

jpalecek
A: 

Put your values in a Map and use a key which wraps your Module object which then properly implements equals and hashCode.

Steve Kuo
A: 

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.

Peter Lawrey
A: 

You could try my Linked Tree Map implementation.

Software Monkey
A: 

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.

jvdneste