2018年11月3日 星期六

java 泛型 exam


package test_1.t1;

/**
 *
 * @author xman
 */
public class T_4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Container<A> c_1 = new Container<A>();
        c_1.add(new B());
        c_1.add(new C());

        Container<? extends A> c_2 = c_1;

        A a_1;

        for (int i = 0; i < 2; i++) {
            a_1 = c_2.get();
            System.out.println(a_1.getName());
        }
        // ------------------
        // 重設指針
        c_2.resetGetPoint();
        // ------------------
        A aa_1;

        // T 確定為 A
        Container<? super A> c_3 = c_1;

        c_3.add(new B());

        for (int i = 0; i < 3; i++) {
            aa_1 = c_2.get();
            System.out.println(aa_1.getName());
        }
    }

}

class Container<T extends A> {

    Object[] data;

    int set_index = 0;
    int get_index = 0;

    public Container() {
        data = new Object[10];
    }

    public void add(T item) {
        this.data[set_index++] = item;
    }

    public T get() {
        T item = (T) this.data[get_index++];
        return item;
    }

    public void resetGetPoint() {
        get_index = 0;
    }
}
//================================================
class A {

    String name;

    public A() {
        this.name = "A";
    }

    public A(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

class B extends A {

    public B() {
        super("B");
    }

    public B(String name) {
        super(name);
    }
}

class C extends B {
    public C() {
        super("C");
    }

}