简体   繁体   English

为什么我的代码仍然显示警告:`警告:[未选中]未选中强制转换?

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

Why does my code still have the warning: warning: [unchecked] unchecked cast ? 为什么我的代码仍然有警告: warning: [unchecked] unchecked cast When I use '-Xlint', the return is as this : 当我使用'-Xlint'时,返回结果如下:

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

But I do not understand it. 但是我不明白。 I used 'LinkedList'. 我使用了“ LinkedList”。 could anyone give a help ? 有人可以帮忙吗?

The below is my code. 下面是我的代码。

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());

    }
}

You are getting an unchecked cast warning because clone returns an Object , not a LinkedList<String> . 您将收到未经检查的强制转换警告,因为clone返回的是Object ,而不是LinkedList<String> The compiler just sees that clone returns an Object , so casting to a generic LinkedList<String> will cause this warning. 编译器只看到clone返回一个Object ,因此强制转换为通用LinkedList<String>会导致此警告。 Because clone loses any type information, using clone there is no way to avoid this warning without @SuppressWarnings . 由于clone会丢失任何类型信息,因此如果没有@SuppressWarnings ,使用克隆将无法避免此警告。

You can however just create a new LinkedList by using the constructor that takes a Collection as its argument. 但是,您可以通过使用Collection作为其参数的构造函数来创建新的LinkedList

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

It is due to type erasure . 这是由于类型擦除引起的 The compiled code will actually look like that : 编译后的代码实际上看起来像这样:

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

Thus, type safety is no longer guaranteed. 因此,不再保证类型安全。

Thats because there is a chance for a ClassCastException to occur. 那是因为有可能发生ClassCastException The compiler is not sure if its safe to cast it that way. 编译器不确定以这种方式进行转换是否安全。 Since you know beforehand that it has to be a LinkedList<String> , you could use the @SuppressWarnings annotation but I would suggest not to do the unchecked cast. 既然您已经事先知道它必须是LinkedList<String> ,则可以使用@SuppressWarnings批注,但我建议不要进行未经检查的强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM