繁体   English   中英

将对象强制转换为通用对象(或将内部类变量存储为通用对象)

[英]Casting an object to a generic (or storing inner class variable as generic)

当我尝试从对象强制转换为通用类型时,我收到警告。 由于内部Node类上的基础数据结构是数组,因此无法使Node通用,因为无法创建通用数组,因此val参数必须为Object。

有什么解决方法或更好的方法吗? 我可以抑制警告,但是不确定是否会引起我应关注的后果。

我还制作了实现MyTreeI的不同树,并且它们都将具有不同的Node结构(所以我不能只制作一个实际的Node类(这是否还能工作?我不知道。。也许))

此处的代码:

public class MyTree<E> implements MyTreeI<E> {
    private Node root;      // root of tree


    private static class Node {
        private Object val;
        private Node[] children = new Node[2];
    }

    public MyTree() {
    }


    @Override
    public E get(String key) {
        Node x = getNode(key); // helper function, assume it returns node in question
        return (E) x.val;
    }
}

由于无法创建通用数组,所以无法使Node通用

使Node通用并不会阻止您使用Node数组。 您不能创建new Node<E>[...] ,是的; 但是您可以创建new Node<?>[...]new Node[...]并将其强制转换为Node<E>[] ,或仅将children的类型更改为Node<?>[] 有很多可能的方法可以做到这一点。

public class MyTree<E> implements MyTreeI<E> {
    private Node<E> root;      // root of tree


    private static class Node<E> {
        private E val;
        private Node<E>[] children = (Node<E>[])new Node<?>[2];
    }

    public MyTree() {
    }


    @Override
    public E get(String key) {
        Node<E> x = getNode(key); // helper function, assume it returns node in question
        return x.val;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM