2013년 8월 12일 월요일

Wildcards



Upper Bounded Wildcards

public static void process( List<? extends Foo> list ) { /* ... */ }




Unbounded Wildcards

public static void printList(List<Object> list) {
    for (Object elem : list)
        System.out.println(elem + " ");
    System.out.println();
}


public static void printList( List<?> list ) {
    for (Object elem: list)
        System.out.print(elem + " ");
    System.out.println();
}


The goal of printList is to print a list of any type, but it fails to achieve that goal —
it prints only a list of Object instances;
it cannot print List<Integer>, List<String>, List<Double>, and so on,
because they are not subtypes of List<Object>.
To write a generic printList method, use List<?>


List<?>. This is called a list of unknown type.




Lower Bounded Wildcards

public static void addNumbers( List<? super Integer> list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}

















댓글 없음:

댓글 쓰기