[英]How to construct such generic class?
public class Matrix<TValue, TList extends List<E>> {
private TList<TList<TValue>> items;
}
我想使用Matrix
类的2个实例。 一个使用ArrayList<Integer>
,第二个使用LinkedList<Integer>
。
不幸的是,要编写一个包含想要的列表列表的通用对象是非常困难的。
这是因为java wich中的类型擦除意味着:
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();;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.