How to cast generic List types in java?

后端 未结 9 989
离开以前
离开以前 2020-12-09 17:33

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

9条回答
  •  粉色の甜心
    2020-12-09 18:25

    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 ll = someList;
    List 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 ll = someList;
    List l = new LinkedList();
    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 ll = new LinkedList();
    List 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.

    提交回复
    热议问题