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 in generic array declaration
java;programming practices;array;generics
@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, sayList<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 castAlso, 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.