HashMap and int as key

前端 未结 11 1996
说谎
说谎 2020-11-28 23:32

I am trying to build a HashMap which will have integer as keys and objects as values.

My syntax is:

HashMap myMap = new HashMap&         


        
相关标签:
11条回答
  • 2020-11-28 23:51

    For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported any more, and I believe it is quite unreliable library (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

    import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;
    
    public class Check {
        public static void main(String[] args) {
            IntObjectHashMap map = new IntObjectHashMap();
    
            map.put(5,"It works");
            map.put(6,"without");
            map.put(7,"boxing!");
    
            System.out.println(map.get(5));
            System.out.println(map.get(6));
            System.out.println(map.get(7));
        }
    }
    

    In this example above IntObjectHashMap.

    As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index, as map is, by nature, an associative array with int type as index.

    0 讨论(0)
  • 2020-11-28 23:54

    Please use HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();

    0 讨论(0)
  • 2020-11-28 23:55

    I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

    An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

    Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

    0 讨论(0)
  • 2020-11-28 23:57

    use int as Object not as primitive type

    HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
    
    0 讨论(0)
  • 2020-11-28 23:58

    You may try to use Trove http://trove.starlight-systems.com/
    TIntObjectHashMap is probably what you are looking for.

    0 讨论(0)
  • 2020-11-28 23:59

    If you code in Android, there is SparseArray, mapping integer to object.

    0 讨论(0)
提交回复
热议问题