Reputation: 3814
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());
}
}
Upvotes: 1
Views: 668
Reputation: 96
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.
Upvotes: 0
Reputation: 25950
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.
Upvotes: 1
Reputation: 178263
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);
Upvotes: 2