在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ java泛型的一些小問題

java泛型的一些小問題

不多說廢話,先上代碼

class Apply {
    // 必須放置邊界和通配符,銀邊使得Apply和FilledList在所有需要的情況下都可以使用,否則,下面的某些Apply和FilledList應(yīng)用將無法工作。
    public static <T, S extends Iterable<? extends T>>
    /*List<Shape> shapes = new ArrayList<Shape>();
        Apply.apply(shapes, Shape.class.getMethod("rotate"));*/
    void apply(S seq, Method f, Object... args) {
        try {
            for(T t: seq)
                f.invoke(t, args);
        } catch(Exception e) {
            // Failures are programmer errors
            throw new RuntimeException(e);
        }
    }
}

class Shape {
    public void rotate() { System.out.println(this + " rotate"); }
    public void resize(int newSize) {
        System.out.println(this + " resize " + newSize);
    }
}

class Square extends Shape {}

class FilledList<T> extends ArrayList<T> {
    // 類型標(biāo)記技術(shù)是Java文獻推薦的技術(shù)。但是,有些人強烈地首先工廠方式
    public FilledList(Class<? extends T> type, int size) {
        try {
            for(int i = 0; i < size; i++)
                // Assumes default constructor:
                add(type.newInstance());
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}

public class Chapter15_17_2 {
    public static void main(String[] args) throws Exception {
        List<Shape> shapes = new ArrayList<Shape>();
        for(int i = 0; i < 10; i++)
            shapes.add(new Shape());
        Apply.apply(shapes, Shape.class.getMethod("rotate"));
        Apply.apply(shapes,
                Shape.class.getMethod("resize", int.class), 5);
        List<Square> squares = new ArrayList<Square>();
        for(int i = 0; i < 10; i++)
            squares.add(new Square());
        Apply.apply(squares, Shape.class.getMethod("rotate"));
        Apply.apply(squares,
                Shape.class.getMethod("resize", int.class), 5);

        Apply.apply(new FilledList<Shape>(Shape.class, 10),
                Shape.class.getMethod("rotate"));
        Apply.apply(new FilledList<Shape>(Square.class, 10),
                Shape.class.getMethod("rotate"));
    }
}

經(jīng)過編譯發(fā)現(xiàn)上面這段代碼是可以運行的,但是對這語句很困惑:public static <T, S extends Iterable<? extends T>>
那位表哥能解釋下具體的意思,以及泛型T是如何來進行賦值的,感激不盡

回答
編輯回答
何蘇葉

不是賦值,而是在編譯時指定某個類型,比如調(diào)用時apply(new Integer(1),Arrays.asList(1,2,3)), T就是 Integer

2017年9月21日 00:29