Well, I have a class Customer (no base class).
I need to cast from LinkedList to List. Is there any clean way to do this?
Just so you know, I need to cast it to List. No other type will do. (I'm developing a test fixture using Slim and FitNesse).
EDIT: Okay, I think I need to give code examples here.
import java.util.*;
public class CustomerCollection
{
protected LinkedList<Customer> theList;
public CustomerCollection()
{
theList = new LinkedList<Customer>();
}
public void addCustomer(Customer c){ theList.add(c); }
public List<Object> getList()
{
return (List<? extends Object>) theList;
}
}
So in accordance with Yuval A's remarks, I've finally written the code this way. But I get this error:
CustomerCollection.java:31: incompatible types
found : java.util.List<capture#824 of ? extends java.lang.Object>
required: java.util.List<java.lang.Object>
return (List<? extends Object>)theList;
^
1 error
So, what's the correct way to do this cast?
The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.
Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.
Cast a list of subtypes to a list of supertypes. The best way I have found is as follows: List<TestA> testAs = List. copyOf( testBs );
You do not need to cast. LinkedList
implements List
so you have no casting to do here.
Even when you want to down-cast to a List
of Object
s you can do it with generics like in the following code:
LinkedList<E> ll = someList;
List<? extends Object> l = ll; // perfectly fine, no casting needed
Now, after your edit I understand what you are trying to do, and it is something that is not possible, without creating a new List
like so:
LinkedList<E> ll = someList;
List<Object> l = new LinkedList<Object>();
for (E e : ll) {
l.add((Object) e); // need to cast each object specifically
}
and I'll explain why this is not possible otherwise. Consider this:
LinkedList<String> ll = new LinkedList<String>();
List<Object> l = ll; // ERROR, but suppose this was possible
l.add((Object) new Integer(5)); // now what? How is an int a String???
For more info, see the Sun Java generics tutorial. Hope this clarifies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With