How to cast generic List types in java?

后端 未结 9 985
离开以前
离开以前 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:27

    I did this function for that, ugly but it works

    public static <T> Collection<T> cast(Collection<? super T> collection, Class<T> clazz){
        return (Collection<T>)collection;
    }
    
    0 讨论(0)
  • 2020-12-09 18:30

    Here's my horrible solution for doing casting. I know, I know, I shouldn't be releasing something like this into the wild, but it has come in handy for casting any object to any type:

    public class UnsafeCastUtil {
    
        private UnsafeCastUtil(){ /* not instatiable */}
    
        /**
        * Warning! Using this method is a sin against the gods of programming!
        */
        @SuppressWarnings("unchecked")
        public static <T> T cast(Object o){
            return (T)o;
        }
    
    }
    

    Usage:

    Cat c = new Cat();
    Dog d = UnsafeCastUtil.cast(c);
    

    Now I'm going to pray to the gods of programming for my sins...

    0 讨论(0)
  • 2020-12-09 18:35

    List is an interface, LinkedList is a concrete implementation of that interface. Much of the time an implicit cast will work, assign a LinkedList to a List, or pass it to a function expecting a List and it should just `work'.

    An explicit cast can also be done if necessary.

    //This is valid
    List<Customer> myList = new LinkedList<Customer>();
    
    //Also Valid
    List<Customer> myList = (List<Customer>) new LinkedList<Customer>();
    
    0 讨论(0)
提交回复
热议问题