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
    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?

3 Answers 3


@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.

  • 4
    I'll have to disagree on 'converting' the @SuppressWarnings annotation to a standard comment. For starters, @SuppressWarnings can be used on the specific lines, not just for methods. Second, if you ever did fix the unchecked casting in the future, a good IDE (settings-dependent) will helpfully point you out that the annotation is no longer required. Third, and depending on your school of thought, comments tend to snowball to become its own form of 'comment smell' in the long run, which may lead to misunderstandings.
    – h.j.k.
    Sep 26, 2014 at 2:08
  • That's a good point. It can be used on variable declarations, but not on statements in general. I've edited my example to show a line that can't be annotated. I personally don't use an IDE (nor do any of my coworkers), so if javac doesn't catch it, I comment it. I'll admit I'd probably forgo these comments if we all used IDEs. Sep 26, 2014 at 2:26
  • Yeah, I over-generalized by saying specific lines when the closest is actually variable declarations, as you have mentioned. Just in case anyone needs to consult the API (circa September 2014): docs.oracle.com/javase/8/docs/api/java/lang/… Now I see where you are coming from...
    – h.j.k.
    Sep 26, 2014 at 2:34
  • You are correct, there are certain things that a human can look at and know are not risky and therefor should have that annotation but a compiler or IDE cannot know for sure (unless you are compiling on Skynet). But I would not add a comment: the annotation itself serves the same purpose as a comment.
    – user22815
    Sep 26, 2014 at 4:24
  • 1
    Due to the issues around Generified types, type erasure and co-variance, arrays are de facto now a deprecated language element. Don't feel bad about having to suppress type warnings when working with arrays; it's perhaps the most appropriate use of "Suppress" of all. Sep 26, 2014 at 6:44

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>();

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:


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 Es into it):

public class GenSet<E> {
  private Object[] a;

  public GenSet(int s) {
    this.a = new Object[s];

  E get(int i) {
    return (E)a[i];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.