Can I use generics over reference types only?

Yes, you can only use reference types for generic type parameters, and yes, there will be some performance penalty due to boxing/unboxing (which can be done automatically for the most part).

Here’s a quote from the Java Generics FAQs:

Are primitive types permitted as type arguments?

No. Only reference types can be used as type arguments.
A parameterized type such as List<int> or Set<short> is illegal. Only reference types can be used for instantiation of generic types and methods. Instead of List<int> we must declare a List<Integer>, using the corresponding wrapper type as the type argument.

[…] Note, that the lack of primitive type instantiations incurs a performance penalty. Autoboxing and -unboxing make the use of wrapper type instantiations of generic types very convenient and concise in the source code. But the concise notation hides the fact that behind the curtain the virtual machine creates and uses lots of wrapper objects, each of which must be allocated and later garbage collected. The higher performance of direct use of primitive type values cannot be achieved with generic types. Only a regular type can provide the optimal performance of using primitive type values.

If you absolutely need the performance, Trove has many data structures specialized for primitive types, but for most practical purposes, using boxed primitive types with Java Collections Framework classes should yield more than acceptable performance.

See also

Leave a Comment