How to properly return generic array in Java generic method?

前端 未结 3 449
逝去的感伤
逝去的感伤 2021-02-03 12:09

I have below generic method that returns a generic array:

public static  T[] genericMethod1(List input) {
    T[] res = (T[]) new Object[input.s         


        
3条回答
  •  情书的邮戳
    2021-02-03 12:26

    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.

提交回复
热议问题