I have a model class that stores keys and values:
public class KeyValue {
private Object key;
private String value;
KeyValue () {
}
KeyValue (Object key, String value) {
this.key=key;
this.value=value;
}
public Object getKey() {
return this.key;
}
public void setKey(Object key) {
this.key=key;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value=value;
}
@Override
public String toString() {
return this.value;
}
}
I use this class to populate a JComboBox‘s Model:
for (int i = 0; i < universes.length; i++) {
ComboBox_Universes.addItem(new KeyValue(infoObject.ID,infoObject.title));
}
I would like to refactor this logic to use a Java collection class (call it KeyValueCollection) that can support two objectives:
1) the KeyValueCollection can be used to populate the JComboBox‘s Model. Something like:
//get a KeyValueCollection filled with data from helper class
KeyValueCollection universeCollection = Repository.getUniverseCollection();
//use this collection as the JComboBox's model
ComboBox_Universes.setModel(universeCollection);
2) I can use the KeyValueCollection to convert a key to a value:
//ID retrieve from another control
int universeID = (int)this.Table_Values.getModel().getValueAt(row, COLUMN_ID);
//convert ID to name
String universeName = universeCollection.get(universeID).getValue();
In the .NET world, I would use the KeyedCollection class for this, but I’m not very familiar with Java.
Help is greatly appreciated.
You can use a custom class like this one (run main function to see its behavior) :
EDIT : to handle the selected item and keys, you may add these methods:
By default, values are ordered following the natural order of the keys (alphabetical order of the keys, here, because these are
String). If you need an other ordering, add ajava.util.Comparatorto theTreeMap(see TreeMap documentation).