Bobby
Bobby

Reputation: 18305

How can I add the keys of a LinkedHashMap to a JList?

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.

Upvotes: 1

Views: 2028

Answers (3)

Michael Myers
Michael Myers

Reputation: 191955

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.

Upvotes: 1

Kathy Van Stone
Kathy Van Stone

Reputation: 26291

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.

Upvotes: 1

Bobby
Bobby

Reputation: 18305

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());

Upvotes: 0

Related Questions