集册 Java实例教程 创建泛型框类

创建泛型框类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

418
创建泛型框类

/**

 * Generic version of the Box class.

 * @param <T> the type of value being boxed

 *//** 时   代     Java  公  众  号 - nowjava.com 提 供 **/

class Box<T> {


    private T t; // T stands for "Type"          


    public void set(T t) {

        this.t = t;

    }


    public T get() {

        return t;

    }

}


public class BoxDemo {


    public static <U> void addBox(U u, java.util.List<Box<U>> boxes) {

        Box<U> box = new Box<>();/** 来 自 时 代      J a v a   公   众 号 - nowjava.com**/

        box.set(u);

        boxes.add(box);

    }


    public static <U> void outputBoxes(java.util.List<Box<U>> boxes) {

        int counter = 0;

        for (Box<U> box : boxes) {

            U boxContents = box.get();

            System.out.println("Box #" + counter + " contains ["

                    + boxContents.toString() + "]");

            counter++;

        }

    }


    public static void main(String[] args) {

        java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();

        BoxDemo.<Integer> addBox(Integer.valueOf(10), listOfIntegerBoxes);

        BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);

        BoxDemo.addBox(Integer.valueOf(30), listOfIntegerBoxes);

        BoxDemo.outputBoxes(listOfIntegerBoxes);

    }

}


展开阅读全文