I have below generic method that returns a generic array:
public static T[] genericMethod1(List input) {
T[] res = (T[]) new Object[input.s
When calling the method, genericMethod you are assuming that it returns array of integers, which is NOT correct. It actually returns array of type Object at runtime.
List input = new ArrayList();
input.add(1);
Object[] output = genericMethod(input);
for(Object obj : output){
System.out.println("Value= "+ (Integer)obj);
}
So we need to cast the individual content of the array.
One general guidline is that we shouldn't mix ARRAY and GENERICS in Java.
Update:
Reference from Effective Java:
In Summary, arrays and generics have very different type rules. Arrays are covariant and reified; generics are invariant and erased. As a consequcne, arrays provide runtime type safety but not compile-time type safety and vice versa for generics. Generally speaking, arrays and generics don’t mix well. If you find yourself mixing them and getting compile-time error or warnings, your first impulse should be to replace the arrays with lists.