簡體   English   中英

Java中“未檢查的強制轉換”警告的解釋

[英]Explanation of “Unchecked cast” warning in Java

我只是一個初學者,我想要一個好的靈魂來幫助我;)我得到了這種方法,然后就可以了:

( (HashSet<String>) pos[targetPos]).add(word);

它給了我一個例外

    (Unchecked cast from Object to HashSet<String>)

我試圖將Object [pos]更改為String [pos]更具體,但隨后在此行上給了我一個錯誤: pos[targetPos] = new HashSet<String>();

Type mismatch: cannot convert from HashSet<String> to String

這是方法:

public void add(String word, Object[] root){

    Object[] pos = root;
    int wordIndex = 0;
    int targetPos;

    if(word.length()>=3){
        for(int i = 1; i <=3; i++){
            targetPos = word.charAt(wordIndex) -'a'; //convert a letter into index eg a==0
            if(i==3){
                if(pos[targetPos]==null){
                    pos[targetPos] = new HashSet<String>();
                }
                ( (HashSet<String>) pos[targetPos]).add(word);
                //System.out.println(Arrays.toString(pos));
                break;

            }//end if outer if
            else{
                if(pos[targetPos]==null){
                    pos[targetPos] = new Object[28];
                }
                wordIndex++;
                pos =  (Object[]) pos[targetPos];
            }
        }//end of for
    }

}

根是

 Object[] root = new Object[28];

“未經檢查的演員表”消息是警告。 編譯器警告您,無法確定從ObjectHashSet<String>的顯式HashSet<String>可以在運行時安全地進行,這意味着,如果您的Object類型的數組包含除HashSet<String>之外的其他內容 ,則可能當JVM嘗試將該對象轉換為HashSet<String>類型時,將在運行時獲取ClassCastException 本質上,編譯器會事先警告您,您正在做某些可能不安全的操作,以后可能會引起問題。

簡單地使用數組的原始對象不是一個好習慣。 如果要確保該數組僅包含HashSet<String>對象,則可能應該這樣鍵入它(即Set<String>[] ;使用接口而不是該類型的具體實現)因為這樣您就可以在需要時切換實現)。 唯一應該進行顯式轉換的時間是,您可以絕對確定要轉換的對象絕對是您要轉換到的對象的類型。 例如,如果您有一個實現接口的對象,並且還假設您屬於某個類中,那么該類肯定可以使用該接口的特定具體實現。 在這種情況下,可以將其從該接口轉換為具體類型。

您的方法應如下所示:

public void add(String word, Set<String>[] root){

    Set<String>[] pos = root; //You probably don't even need this since you have "root"
    ...
}

此外,考慮使用一個ListSet<String>而不是數組:

public void add(String word, List<Set<String>> root){

    List<Set<String>> pos = root; //You probably don't even need this since you have "root"
    ...
}

pos[]被定義為Object數組。 稍后將其轉換為HashSet<String> ,Java不知道您可以這樣做。 這就是未經檢查的強制轉換-編譯器警告您,您可能正在做某些不安全的事情。

您可以通過將pos的類型更改為HashSet<String>[]來消除警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM