How do java generic methods limit method type arguments?

I read about general methods and thought I understood how the generic type argument would limit the types of method parameters, but when I tested some ideas with real code, I got unexpected results. Here is a simple general method that I do not understand:

private static <T> void foo(T[] t1, T[] t2){  
    t2[0] = t1[0];
}
...
String[] stringArray = new String[]{"1", "2", "3"};
Integer[] integerArray = new Integer[]{4,5,6};
foo(stringArray, integerArray);

I would have thought that this general method was limited, so the two arrays were supposed to be of the same type T, but in practice the above code compiles just fine, although one array is of type String and the other is type Integer. When a program starts, it throws an exception at runtime (ArrayStoreException).

+3
source share
4 answers

? extends Object[], .

:

private static <T> void foo(Class<T> clazz, T[] t1, T[] t2);

foo(String.class, stringArray, stringArray); // compiles
foo(String.class, stringArray, integerArray); // fails
+1

Java , String[] Object[] ( List<String> List<Object>). , T= Object,

foo(Object[] t1, Object[] t2)

foo(stringArray, integerArray).

:

<T> void foo(List<T> t1, List<T> t2) { ... }

,

foo(new ArrayList<String>(), new ArrayList<Integer>())

- T, List<String> List<Integer> List<T>. , :

void foo(List<?> t1, List<?> t2) { ... }

( , , ? ).

+1

@Bozho, , , , , :

public class Main {


  // This is the original version that fails because of type erasure in arrays
  private static <T> void foo(T[] t1, T[] t2) {

    t2[0] = t1[0];
  }

  // The same method as foo() but with the type erasure demonstrated
  private static void foo2(Object[] t1, Object[] t2) {

    // Integer[] should not contain String 
    t2[0] = t1[0];
  }


  public static void main(String[] args) {

    String[] stringArray = new String[]{"1", "2", "3"};
    Integer[] integerArray = new Integer[]{4, 5, 6};

    foo2(stringArray, integerArray);
  }

}

, Java , generics - . . :

Java - , ( ), Integer , [] [], [], a []. ( , Number Integer, Number [] Integer [].) , - List, , . , .

, : , . , . , :

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));

ln - List, Float . aliased li, , li, - , .

+1

T , , Object.

, , :

MyClass.<String>foo(stringArray, integerArray); // Compiler error.

. Angelika Langer Generics: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

0

Source: https://habr.com/ru/post/1773960/


All Articles