当前位置 : 主页 > 手机开发 > harmonyos >

【陷阱】封装带有变长泛型参数时的易犯错误

来源:互联网 收集:自由互联 发布时间:2023-08-25
泛型几乎都用‘E’来表示,写着写着就弄混淆了 如下: class GenericArrayProblem { public static void main(String[] args) { // Exception in thread "main" java.lang.ClassCastException: // [Ljava.lang.Object; cannot be cas


泛型几乎都用‘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);
    }
}



 

上一篇:oracle存储过程杂记
下一篇:没有了
网友评论