泛型几乎都用‘E’来表示,写着写着就弄混淆了

如下:



class GenericArrayProblem {

    public static void main(String[] args) {

        // Exception in thread "main" java.lang.ClassCastException:
        // [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
        new PrinterWrapper<String>("abc", new StringPrinter()).print();
    }
}

class PrinterWrapper<E> {

    private E element;
    private Printer<E> printer;

    PrinterWrapper(E element, Printer<E> printer) {

        this.element = element;
        this.printer = printer;
    }

    void print() {

        this.printer.print(element);
    }
}

abstract class Printer<E> {

    abstract void print(E... elements);
}

class StringPrinter extends Printer<String> {

    @Override
    void print(String... elements) {

        for (String s : elements)
            System.out.println(s);
    }
}



可以改为:



class PrinterWrapper<E> {

    private E[] element;
    private Printer<E> printer;

    PrinterWrapper(E[] element, Printer<E> printer) {

        this.element = element;
        this.printer = printer;
    }

    void print() {
        this.printer.print(element);
    }
}



或者



class PrinterWrapper<E> {

    private E[] element;
    private Printer<E> printer;

    PrinterWrapper(Printer<E> printer,E...element) {

        this.element = element;
        this.printer = printer;
    }

    void print() {
        this.printer.print(element);
    }
}