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
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;
}
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...
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>();