简体   繁体   中英

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

Why does my code still have the warning: warning: [unchecked] unchecked cast ? When I use '-Xlint', the return is as this :

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'. 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> . The compiler just sees that clone returns an Object , so casting to a generic LinkedList<String> will cause this warning. Because clone loses any type information, using clone there is no way to avoid this warning without @SuppressWarnings .

You can however just create a new LinkedList by using the constructor that takes a Collection as its argument.

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. 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.

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.

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