While doing a coding test, I ran into a problem where I need to initialize an array of generic type in Java. While trying to figure out how to do that, I looked at this Stack Overflow question and it requires that I suppress a warning which doesn’t seem like a good practice, and might have other type safety issues. For clarity, here is the code:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}
Does this mean I am going about the problem wrong? Is it ok to have the @SuppressWarnings("unchecked")
in this case?
Should I just use an ArrayList
?
@SuppressWarnings("unchecked")
is sometimes correct and unavoidable in well-written code. Creating an array of generic types is one case. If you can work around it by using a Collection<T>
or List<T>
of generics then I’d suggest that, but if only an array will do, then there’s nothing you can do.
Casting to a generic type is another similar case. Generic casts can’t be verified at runtime, so you will get a warning if you do, say
List<Integer> numbers = (List<Integer>) object;
That doesn’t make it bad style to have generic casts. It simply reflects a limitation of the way generics were designed in Java.
To acknowledge that I’m intentionally writing code with warnings, I’ve made it a rule to add a comment to any such lines. This makes the choice stand out. It also makes it easy to spot these lines, since @SuppressWarnings
can’t always be used directly on the target lines. If it’s at the top of the method it might not be obvious which line or lines generate warnings.
((List<Integer>) object).add(1); // warning: [unchecked] unchecked cast
Also, to be clear, you should not work around this with a raw type (List
instead of List<T>
). That is a bad idea. It will also produce warnings if you enable -Xlint
, so wouldn’t really make the situation any better, anyways.
5
Based on the fact you are asking if you should use ArrayList
instead, I assume the use of an array is not a requirement. I would use the ArrayList
or other collection and rely on interfaces, not implementations, to reference it:
List<Integer> myInts = new ArrayList<Integer>();
myInts.add(4);
Java generics are in a tough position. On one hand, Java has the self-imposed (but good) goal of being backwards compatible. Since generics are essentially incompatible with pre-1.5 bytecode, this results in type erasure. Essentially, the generic type is removed at compile time and generic method calls and accesses are reinforced with type casts instead. On the other hand, this limitation makes generic references really messy sometimes to the point that you must use @SuppressWarnings
for unchecked and raw types at times.
What this means is that collections that rely on method calls to insulate users of a collection from the storage work fine, but arrays are reified which means that per the language, array types must be available at runtime. This runs counter to collections which as I mentioned have the generic type erased. Example:
String[] array1 = new String[1];
Object[] array2 = array1;
Despite the reference array2
being declared as Object[]
, the JVM knows the array it targets can only hold strings. Because these types are reifable, they are essentially incompatible with generics.
StackOverflow has many questions on the topic of Java generics and arrays, here are a few good ones I found:
- How to: generic array creation
- Generic arrays in Java
In this case, it is perfectly okay to suppress the unchecked cast warning.
It’s an unchecked cast because E
is not known at runtime. So the runtime check can only check the cast up to Object[]
(the erasure of E[]
), but not actually up to E[]
itself. (So for example, if E
were Integer
, then if the object’s actual runtime class was String[]
, it would not be caught by the check even though it’s not Integer[]
.)
Array.newInstance()
returns Object
, and not E[]
(where E
would be the type argument of the Class
parameter), because it can be used to create both arrays of primitives and arrays of references. Type variables like E
cannot represent primitive types, and the only supertype of array-of-primitive types is Object
. Class
objects representing primitive types are Class
parameterized with its wrapper class as the type parameter, e.g. int.class
has type Class<Integer>
. But if you pass int.class
to Array.newInstance()
, you will create an int[]
, not E[]
(which would be Integer[]
). But if you pass a Class<E>
representing a reference type, Array.newInstance()
will return an E[]
.
So basically, calling Array.newInstance()
with a Class<E>
will always return either an E[]
, or an array of primitives. An array-of-primitives type is not a subtype of Object[]
, so it would fail a runtime check for Object[]
. In other words, if the result is an Object[]
, it is guaranteed to be an E[]
. So even though this cast only checks up to Object[]
at runtime, and it doesn’t check the part from Object[]
up to E[]
, in this case, the check up to Object[]
is sufficient to guarantee that it is an E[]
, and so the unchecked part is not an issue in this case, and it is effectively a fully checked cast.
By the way, from the code you have shown, you do not need to pass a class object to initialize GenSet
or to use Array.newInstance()
. That would only be necessary if your class actually used the class E
at runtime. But it doesn’t. All it does is create an array (that is not exposed to the outside of the class), and get elements from it. That can be achieved using an Object[]
. You just need to cast to E
when you take an element out (which is unchecked by which we know to be safe if we only put E
s into it):
public class GenSet<E> {
private Object[] a;
public GenSet(int s) {
this.a = new Object[s];
}
@SuppressWarnings("unchecked")
E get(int i) {
return (E)a[i];
}
}