Java – How to cast generic List types in java


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: 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?

Best Solution

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