如何构建这样的泛型类?

时间:2011-09-04 15:41:59

标签: java generics

public class Matrix<TValue, TList extends List<E>> {
    private TList<TList<TValue>> items;
}

我想使用Matrix类的2个实例。一个ArrayList<Integer>,第二个LinkedList<Integer>

1 个答案:

答案 0 :(得分:3)

不幸的是,编写一个包含列表列表的通用对象非常困难。

这是因为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();;
    }