Why does this give me a type safety warning?
MyAwesomeObject<T>[] parent = new MyAwesomeObject[1];
Why does this give me a type safety warning?
MyAwesomeObject<T>[] parent = new MyAwesomeObject[1];
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.