2

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.

c0der
  • 18,467
  • 6
  • 33
  • 65
Teju
  • 47
  • 1
  • 7

3 Answers3

3

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Primitives can not be used in generics. So you have to use Wrapper Types.

But using primitive arrays is okay, because Java-Arrays are always objects.

If you want to use primitives then have a look at Project Valhalla. Which wants to get rid of a lot of garbage in java and implements Value Types (similar to primitives)

Lino
  • 19,604
  • 6
  • 47
  • 65
1

Map does not allow primitive type as key or value. int[] works because according to Java doc array is an Object.

If you want to use custom object as key/value you should either make that class immutable or have to override hashCode() and equals() method.

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23