I have a question concerning some semantics when instantiating a Map. Specifically, should I use the Wrapper class when assigning the key and value type, or is it okay to use primitive types?
Example:
Map<int, String> map = new TreeMap<int, String>();
OR
Map<Integer, String> map = new TreeMap<Integer, String>();
Example:
Map<int[], String> map = new TreeMap<int[], String>();
OR
Map<Integer[], String> map = new TreeMap<Integer[], String>();
Is there any difference between the two instantiations, in terms of both convention and meaning? I know using primitive types invokes Autoboxing when the object is read or written to.
You can't use a primitive type in a generic type specification (such as Map<int, String>
you suggested above), so you'll have to use the wrapper classes (i.e., Map<Integer, String>
for this usecase). You can, of course, still use primitives when calling such a class' methods, as the primitive would be autoboxed (e.g., myMap.put(7, 'Some String')
.
Arrays are a different question. Primitive arrays are in fact Objects so you could use them in generic specifications. However, arrays don't override the equals(Object)
and hashCode()
methods (regardless of whether they're arrays of primitives or objects), which makes them a very poor choice for map keys.