簡體   English   中英

為什么我的代碼仍然顯示警告:`警告:[未選中]未選中強制轉換?

[英]Why does my code still have the warning: `warning: [unchecked] unchecked cast`?

為什么我的代碼仍然有警告: warning: [unchecked] unchecked cast 當我使用'-Xlint'時,返回結果如下:

demo1.java:31: warning: [unchecked] unchecked cast
        LinkedList<String> queueB = (LinkedList<String>)(queueA.clone());        
                                                        ^
  required: LinkedList<String>
  found:    Object
1 warning

但是我不明白。 我使用了“ LinkedList”。 有人可以幫忙嗎?

下面是我的代碼。

import java.util.LinkedList;
import java.util.Iterator;

public class demo1
{
    public static void main(String[] args)
    {
        LinkedList<String> queueA = new LinkedList<String>();
        queueA.add("element 1");
        queueA.add("element 2");
        queueA.add("element 3");

        Iterator<String> iterator = queueA.iterator();
        while(iterator.hasNext())
        {
            String element = iterator.next();
        }

        for (Object object : queueA)
        {
            String element = (String) object;
            System.out.println("queueA: "+element);
        }


        LinkedList<String> queueB = (LinkedList<String>)(queueA.clone());        
        System.out.println("queueB," +  queueB.remove());

    }
}

您將收到未經檢查的強制轉換警告,因為clone返回的是Object ,而不是LinkedList<String> 編譯器只看到clone返回一個Object ,因此強制轉換為通用LinkedList<String>會導致此警告。 由於clone會丟失任何類型信息,因此如果沒有@SuppressWarnings ,使用克隆將無法避免此警告。

但是,您可以通過使用Collection作為其參數的構造函數來創建新的LinkedList

LinkedList<String> queueB = new LinkedList<String>(queueA);

這是由於類型擦除引起的 編譯后的代碼實際上看起來像這樣:

LinkedList<String> queueB = (LinkedList)(queueA.clone()); 

因此,不再保證類型安全。

那是因為有可能發生ClassCastException 編譯器不確定以這種方式進行轉換是否安全。 既然您已經事先知道它必須是LinkedList<String> ,則可以使用@SuppressWarnings批注,但我建議不要進行未經檢查的強制轉換。

暫無
暫無

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

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