2015-01-10 5 views
1

독서 Java Generics and Collections book.명시 적 매개 변수

//given 
public static <T> void copy(List<? super T> dst, List<? extends T> src) { 
    .... 
} 

지금, 그것은 말한다 - 대상 및 소스가 정확히 같은 유형 (understood)가 때 통화 만 허용으로 We could also declare the above method with several possible signatures.

public static <T> void copy(List<T> dst, List<T> src)     1 
public static <T> void copy(List<T> dst, List<? extends T> src)   2 
public static <T> void copy(List<? super T> dst, List<T> src)   3 
public static <T> void copy(List<? super T> dst, List<? extends T> src) 4 

이 중 첫 번째는 너무 제한적입니다. ,

Confusing part - - (타입 추론 너 한테 적절한 유형을 추론합니다 understood)하지만 명시 적 형식 매개 변수가 다릅니다

나머지 세 암시 적 형식 매개 변수를 사용하여 통화에 대해 동일합니다. 위 예제 호출의 경우 두 번째 서명은 형식 매개 변수가 Object 인 경우에만 작동하고 세 번째 서명은 형식 매개 변수가 Integer 인 경우에만 작동합니다. 때문에 나는 Confusing part에만 문 6에 따라,

public class AsList { 
    public static void main (String...a) { 
     List<Number> l4 = new ArrayList<Number>(); 
     List<Object> l5 = new ArrayList<Object>(); 
     List<Integer> l6 = new ArrayList<Integer>(); 

     //type is inferred implicitly for the below call 
     copy(l4, Arrays.<Integer>asList(1, 2, 3)); 

     //type is specified explicitly 
     AsList.<Number>copy(l4, Arrays.<Integer>asList(1, 2, 3)); \\why? 5 
     AsList.<Object>copy(l5, Arrays.<Integer>asList(1, 2, 3));   6 
     AsList.<Integer>copy(l6, Arrays.<Integer>asList(1, 2, 3)); \\why? 7 
    } 
    public static <T> void copy(List<T> dst, List<? extends T> src) { 
     for (int i = 0; i < src.size(); i++) { 
      dst.add(src.get(i)); 
     } 
    } 
} 

여기 (아래) 시도 무엇

암 혼란이 실행해야하지만 5 & 7도 노력하고 있습니다. 왜? Confusing part에서 언급

편집 예 호출은 형식 매개 변수가 List<Number>List<? extends Number>있는 경우 5에서 다음과 같이

Collections.copy(objs, ints); 
Collections.<Object>copy(objs, ints); 
Collections.<Number>copy(objs, ints); 
Collections.<Integer>copy(objs, ints); 

답변

1

있습니다. List<Number>List<Integer>에 합격하는 것이 좋습니다.

경우 7의 형식 매개 변수는 List<Integer>List<? extends Integer>입니다. 다시 List<Integer>List<Integer>을 전달하는 것이 좋습니다.

+0

'혼동 부분'의 '2'의 경우 저자가 언급 한 '두 번째 서명은 형식 매개 변수가 Object 인 경우에만 두 번째 서명이 작동합니다.'라는 문장도 이해할 수 없다고 생각합니다. – Tirath

+0

사례 2에서 언급 된 "위의 예제 호출"은 무엇입니까? – Henry

+0

확인. 나는 그것을 지금 이해한다. 저자는 케이스 2가 명시된 명시된 타입이'Object' 인 호출에 대해서만 동작 할 것이라고 말합니다. 옳은? – Tirath