@SuppressWarnings in generic array declaration

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 Es 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];
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật