views:

334

answers:

3

I have a LinkedHashMap<String,Object> and was wondering what the most efficient way to put the String portion of each element in the LinkedHashMap into a JList.

A: 

Found this way to do it just after I answered the question, thought I would put it up here for the community. I think that this is the most efficient way to get it done, but am certainly open to more suggestions.

jList1.setListData(LinkedHashMap.keySet().toArray());
Soldier.moth
As long as you don't expect the JList to update when you add something to the map, this will work.
Michael Myers
You could also use the setListData(Vector) method: jList1.setListData(new Vector<String>(map.keySet()));
Michael Myers
thanks mmyers I think I will use that way instead.
Soldier.moth
Shall I put it in an answer, or do you want to edit it into this one?
Michael Myers
You can go ahead and put it in an answer, I like to give credit where credit is due.
Soldier.moth
+1  A: 

If the jList is not sensitive to changes of the original Map, the original method you used is fine (better than using Vector, which has the extra layer of sychronization).

If you want jList to change when the map changes, then you will have to write your own ListModel (which is not that hard). You will also have to figure out how to know when the map changes.

Kathy Van Stone
What do you mean by the original method is "better than using Vector?" I'm just curious.
Soldier.moth
The Vector class has every method synchronized. This adds a small cost to each call. It is not a big difference, but since the other technique is about as simple, I recommend it over Vectors.
Kathy Van Stone
+1  A: 

You could also use the setListData(Vector) method:

jList1.setListData(new Vector<String>(map.keySet()));

With each of the setListData methods, you're making a copy of the actual data, so changes to the map will not be reflected in the list. You could instead create a custom ListModel and pass it to the setModel method instead, but because there is no way to access an arbitrary element of a LinkedHashMap by index, this is probably infeasible.

Michael Myers