Search code examples
javaarraysindexingdereference

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 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?


Solution

  • 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));
        }
    }