『阿男的Java泛型讲座』*06*Wildcard类型捕获

本节课视频:

『阿男的Java泛型讲座』*06*Wildcard类型捕获

本节课代码:

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:[email protected]">Weinan Li</a>
 */
public class WildcardCapture {

    public static void reverse(List<?> list) {  // equals to <? extends Object>
//        List tmp = new ArrayList(list);
//        for (int i = 0; i < list.size(); i++) {
//            list.set(i, tmp.get(list.size()-i-1)); // violate GET and PUT principle
//        }

        reverse2(list);
    }

    public static <T> void reverse2(List<T> list) {
        List<T> tmp = new ArrayList<>(list);
        for (int i = 0; i < list.size(); i++) {
            list.set(i, tmp.get(list.size() - i - 1));
        }
    }
}

你可能感兴趣的:(java)