How to construct such generic class?
public class Matrix<TValue, TList extends List<E>> {
private TList<TList<TValue>> items;
}
I want to use 2 instanc开发者_Python百科es of Matrix
class. One with ArrayList<Integer>
and second with LinkedList<Integer>
.
Unfortunately, it is very difficult to code a generic object wich contains a list of lists the way you want to.
This is because of type erasure in java wich means:
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
However, if the types of lists you want to use is small, you can do something similar to this example (this one is limited to ArrayList and 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;
}
}
This can be easily initialized and used:
try {
Matrix<Integer> m_ArrayList = new Matrix<Integer>(ArrayList.class);
Matrix<Integer> m_LinkedList = new Matrix<Integer>(LinkedList.class);
} catch (Exception ex) {
ex.printStackTrace();;
}
精彩评论