import java.util.*; public class CustomerCollection { protected LinkedList theList; public CustomerCollection() { theList = new LinkedList(); } public void addCustomer(Customer c){ theList.add(c); } public List getList() { return (List) theList; } }
LinkedList ll = someList; List extends Object> l = ll; // perfectly fine, no casting needed
现在,在您编辑之后,我了解您正在尝试做什么,并且这是不可能的,而不是像这样创建一个新的List :
LinkedList ll = someList; List
我会解释为什么这是不可能的。 考虑一下:
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???
public class UnsafeCastUtil { private UnsafeCastUtil(){ /* not instatiable */} /** * Warning! Using this method is a sin against the gods of programming! */ @SuppressWarnings("unchecked") public static T cast(Object o){ return (T)o; } }
用法:
Cat c = new Cat(); Dog d = UnsafeCastUtil.cast(c);
现在我要为我的罪孽向编程之神祈祷……
我为此做了这个function,丑陋但它有效
public static Collection cast(Collection super T> collection, Class clazz){ return (Collection)collection; }