当我尝试从对象转换为泛型类型时收到警告。
由于我的内部 Node 类上的底层数据结构是一个数组,因此我无法使 Node 通用,因为我无法创建通用数组,因此我的 val
参数必须是一个对象。
有没有解决办法或更好的方法来做到这一点?我可以抑制警告,但我不确定这是否会产生我应该担心的后果。
我还制作了实现 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;
}
}
最佳答案
I can't make Node generic since I can't create generic arrays
制作Node
generic 不会阻止您使用 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;
}
}
关于java - 将对象转换为泛型(或将内部类变量存储为泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20465773/