簡體   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