0

Why does this give me a type safety warning?

MyAwesomeObject<T>[] parent = new MyAwesomeObject[1];
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
user2499298
  • 177
  • 2
  • 5
  • 17
  • possible duplicate of [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) See also: [Java 1.6: Creating an array of List](http://stackoverflow.com/questions/5662394/java-1-6-creating-an-array-of-listt) – Paul Bellora Mar 02 '14 at 05:58

1 Answers1

0

It's because arrays generally don't go well with generic types. The most common way people handle data structures with generic types is to use Lists.

So for example, you would create a List<T> object rather than an array. One reason why arrays don't go well with generics and gives you the type safety warning is because arrays are co-variant: meaning that they can contain sub-types.

For example, an array of objects can contain longs and ints, which would fail at run-time when you tried to call items from the array. With Lists, it prevents you from inserting subtypes at compile time that could cause your code to fail at run-time.

So a rule of thumb would be to use a List instead of an array, but if you're really intent on using arrays and are sure that you will not be inserting any sub-types into the array, then you can add the line @SuppressWarnings("unchecked") above the line that you gave.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
TommyBoy
  • 11
  • 1