2009-03-06 2 views

답변

16

유형 매개 변수가 "출력"위치에서만 사용되기 때문에 수행 할 수있는 작업의 측면에서 실제적인 차이점이 없습니다. 반면에 중 하나로 사용할 수 있다는 점에서 큰 차이가 있습니다.

Enumeration<JarEntry>이 있다고 가정하면 Enumeration<ZipEntry>을 인수로 취한 메서드로 전달할 수 없습니다. 당신은 Enumeration<? extends ZipEntry> 복용 방법으로 전달할 수 있습니다.

입력 위치와 출력 위치 모두에서 type 매개 변수를 사용하는 유형이있는 경우에 더 재미 있습니다. List<T>이 가장 확실한 예입니다. 다음은 매개 변수가 변형 된 메서드의 세 가지 예제입니다. 각각의 경우에 목록에서 항목을 가져 와서 다른 항목을 추가하려고합니다.

// Very strict - only a genuine List<T> will do 
public void Foo(List<T> list) 
{ 
    T element = list.get(0); // Valid 
    list.add(element); // Valid 
} 

// Lax in one way: allows any List that's a List of a type 
// derived from T. 
public void Foo(List<? extends T> list) 
{ 
    T element = list.get(0); // Valid 
    // Invalid - this could be a list of a different type. 
    // We don't want to add an Object to a List<String> 
    list.add(element); 
} 

// Lax in the other way: allows any List that's a List of a type 
// upwards in T's inheritance hierarchy 
public void Foo(List<? super T> list) 
{ 
    // Invalid - we could be asking a List<Object> for a String. 
    T element = list.get(0); 
    // Valid (assuming we get the element from somewhere) 
    // the list must accept a new element of type T 
    list.add(element); 
} 

자세한 내용은 읽기 :

+0

ZipEntrySubclass는 JarEntry와 같습니다 (ZipFile.entries에서 와일드 카드를 사용하는 이유)? –

+0

감사합니다 톰 - 내 대답을 편집합니다 :) –

4

을 네, 바로 sun generics tutorials 중 하나 :

여기 Shape는 세 개의 하위 클래스 인 Circle, Rectangle, 및 Triangle이있는 추상 클래스입니다.

public void draw(List<Shape> shape) { 
    for(Shape s: shape) { 
    s.draw(this); 
    } 
} 

그것은 무승부() 방법 만 모양의 목록을 호출 할 수 있으며, 목록에서 호출 할 수 없음을 주목할 필요가있다 예를 들어 원형, 사각형, 삼각형의 . 방법을하기 위해 다음과 같이이 작성해야, 모양의 모든 종류의 수용 : 이제

public void draw(List<? extends Shape> shape) { 
    // rest of the code is the same 
} 
+0

이번 주 Jon Skeet이 내게 바로 대답을 얻은 것은 이번이 두 번째입니다. 나는 이것을 우리가 Skeeting으로 언급 할 것을 제안한다. – GaryF

+0

소리가 좋습니다. 과거 시제는 어떻게 되겠습니까? 스케이트? "Jon Skeet sket me again!" :) – Epaga

+0

http://stackoverflow.com/questions/305223/jon-skeet-facts/317486#317486 –

0

방금 ​​갔어요 그리고 나는 우리가 C#을 세계에 이상이 있었으면 좋겠다 뭔가를 생각 나게 . Logic and its application to Collections.Generic and inheritance

선택있는 다음과 같습니다 :