简体   繁体   English

如何构造这样的泛型类?

[英]How to construct such generic class?

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

I want to use 2 instances of Matrix class. 我想使用Matrix类的2个实例。 One with ArrayList<Integer> and second with LinkedList<Integer> . 一个使用ArrayList<Integer> ,第二个使用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: 这是因为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

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): 但是,如果要使用的列表类型较小,则可以执行类似于此示例的操作(此示例仅限于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;
    }


}

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();;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM