Two different type indexed array in java
I need an array type for storing objects. But i need two types of access property like this:
array[0] >>> object1
array["a"] >>> object1
This means index 0 (an integer ) and开发者_Go百科 index a (a string) dereferences same object in the array. For storing objects, i think we need collections but how can i do access property that i mentioned above?
Create a map from the string keys to the numeric keys:
Map<String, Integer> keyMap = new HashMap<String, Integer>();
keyMap.put("a", o);
// etc
Then create a List of your objects, where MyObject is the value type:
List<MyObject> theList = new ArrayList<MyObject>();
Access by integer:
MyObject obj = theList.get(0);
Access by String
MyObject obj = theList.get(keyMap.get("a"));
This requires maintaining your key data structure, but allows for access of your values from one data structure.
You can encapsulte that is in a class, if you like:
public class IntAndStringMap<V> {
private Map<String, Integer> keyMap;
private List<V> theList;
public IntAndStringMap() {
keyMap = new HashMap<String, Integer>();
theList = new ArrayList<V>();
}
public void put(int intKey, String stringKey, V value) {
keyMap.put(stringKey, intKey);
theList.ensureCapacity(intKey + 1); // ensure no IndexOutOfBoundsException
theList.set(intKey, value);
}
public V get(int intKey) {
return theList.get(intKey);
}
public V get(String stringKey) {
return theList.get(keyMap.get(stringKey));
}
}
Arrays only support indecies.
It appears you what to be able to look up an object by index and by key. In which case I suggest you have two collections. One for each type of lookup.
List<MyObject> list = new ArrayList<MyObject>();
Map<String, MyObject> map = new HashMapList<MyObject>():
// array[0] >>> object1
MyObject object0 = list.get(0);
// array["a"] >>> object1
MyObject objectA = map.get("a");
精彩评论