public class Matrix<TValue, TList extends List<E>> {
private TList<TList<TValue>> items;
}
我想使用Matrix
類的2個實例。一個是ArrayList<Integer>
,另一個是LinkedList<Integer>
。如何構建這樣的泛型類?
public class Matrix<TValue, TList extends List<E>> {
private TList<TList<TValue>> items;
}
我想使用Matrix
類的2個實例。一個是ArrayList<Integer>
,另一個是LinkedList<Integer>
。如何構建這樣的泛型類?
不幸的是,按照你想要的方式編寫一個包含列表列表的通用對象是非常困難的。
這是因爲在Java至極類型擦除意味着:
LinkedList<Integer> ll = new LinkedList<Integer>();
assert(ll.getClass() == LinkedList.class); // this is always true
LinkedList<String> ll_string = new LinkedList<String>();
assert(ll.getClass() == ll_string.getClass()); // this is also always true
但是,如果你想用列表的類型是小,你可以做同樣的事情到這個例子(這個只限於ArrayList和LinkedList):
public class Matrix <TValue> {
Object items = null;
public <TContainer> Matrix(Class<TContainer> containerClass) throws Exception{
try{
TContainer obj = containerClass.newInstance();
if(obj instanceof ArrayList){
items = new ArrayList<ArrayList<TValue>>();
} else if(obj instanceof LinkedList){
items = new LinkedList<LinkedList<TValue>>();
}
}catch(Exception ie){
throw new Exception("The matrix container could not be intialized.");
}
if(items == null){
throw new Exception("The provided container class is not ArrayList nor LinkedList");
}
}
public List<List<TValue>> getItems(){
return (List<List<TValue>>)items;
}
}
這可以很容易地初始化和使用:
try {
Matrix<Integer> m_ArrayList = new Matrix<Integer>(ArrayList.class);
Matrix<Integer> m_LinkedList = new Matrix<Integer>(LinkedList.class);
} catch (Exception ex) {
ex.printStackTrace();;
}
這是很難得你的文字和代碼一起。當你爲兩個類提供代碼時,它可能會有所幫助,其中一個類使用'ArrayLists'和另一個'LinkedLists',但是執行相同的操作。然後問如何用泛型解決這個問題,然後只有一個泛型類。在目前的狀態下,你的問題實際上不是一個問題,也很不明確。 –