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.
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))
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
Making Node
generic doesn't inhibit you from using arrays of Node
. You can't create new Node<E>[...]
, true; but you can create new Node<?>[...]
or new Node[...]
and cast it to Node<E>[]
, or just change the type of children
to 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.