简体   繁体   English

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

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

I'm getting a warning when I try to cast to a generic type from an Object. 当我尝试从对象强制转换为通用类型时,我收到警告。 Since my underlying data structure on my inner Node class is an array, I can't make Node generic since I can't create generic arrays, and thus my val parameter has to be an Object. 由于内部Node类上的基础数据结构是数组,因此无法使Node通用,因为无法创建通用数组,因此val参数必须为Object。

is there any work around or a better way of doing this? 有什么解决方法或更好的方法吗? I could just suppress warnings but I'm not sure if that's going to have ramifications I should be concerned about. 我可以抑制警告,但是不确定是否会引起我应关注的后果。

I'm also making different trees that implement the MyTreeI and will all have different Node structures (so I can't just make an actual Node class (would that even work? I don't know.. maybe)) 我还制作了实现MyTreeI的不同树,并且它们都将具有不同的Node结构(所以我不能只制作一个实际的Node类(这是否还能工作?我不知道。。也许))

Ex code here: 此处的代码:

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;
    }
}

I can't make Node generic since I can't create generic arrays 由于无法创建通用数组,所以无法使Node通用

Making Node generic doesn't inhibit you from using arrays of Node . 使Node通用并不会阻止您使用Node数组。 You can't create new Node<E>[...] , true; 您不能创建new Node<E>[...] ,是的; but you can create new Node<?>[...] or new Node[...] and cast it to Node<E>[] , or just change the type of children to Node<?>[] . 但是您可以创建new Node<?>[...]new Node[...]并将其强制转换为Node<E>[] ,或仅将children的类型更改为Node<?>[] There are many possible ways to do this. 有很多可能的方法可以做到这一点。

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