시소당
자바에서 generics 는 다음과 같은 형태로 사용된다.
List<Integer > myList = new LinkedList<Integer >();
오늘 작업을 하다 다음과 같은 코드를 작성하였는데 자꾸 에러 메세지가 나왔다.
Class<? extends MyClass >[] classList = new Class<? extends MyClass >[] { MySubClass.class };
위 코드를 다음과 같이 쓰면 에러 메세지는 더이상 나타나지 않았다.
Class<? extends MyClass >[] classList = new Class[] { MySubClass.class };
이클립스에서도 뒷부분의 new Class... 부분을 경고하고, 내가 생각하기에도 먼저 적은 코드가 맞는 듯 하여 구글링을 잠시 하여 다음과 같은 것을 찾았다.
IBM DeveloperNetworks - Java theory and pratice : Generics gotchas
이 중 이와 관련된 부분만 보면 다음과 같다.
More covariance troubles
Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal). Let's see what would happen if you were allowed to declare arrays of generic types:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
The last line will throw a ClassCastException, because you've managed to cram a List<Integer> into what should have been a List<String>. Because array covariance would have allowed you to subvert the type safety of generics, instantiating arrays of generic types (except for types whose type arguments are unbounded wildcards, like List<?>) has been disallowed.
위에서 예로 든 상황을 막기 위해 배열 선언 시에는 <?> 만을 쓸 수 있게 했다고 한다.
이클립스가 이러한 예외적인 사항에 대해 체크를 하지 못하고 경고를 하는 바람에 더 고생한 듯 하다.
출처 : http://jiho.isdream.kr/8