2011-09-04 99 views
-1
public class Matrix<TValue, TList extends List<E>> { 
    private TList<TList<TValue>> items; 
} 

我想使用Matrix类的2个实例。一个是ArrayList<Integer>,另一个是LinkedList<Integer>如何构建这样的泛型类?

+1

这是很难得你的文字和代码一起。当你为两个类提供代码时,它可能会有所帮助,其中一个类使用'ArrayLists'和另一个'LinkedLists',但是执行相同的操作。然后问如何用泛型解决这个问题,然后只有一个泛型类。在目前的状态下,你的问题实际上不是一个问题,也很不明确。 –

回答

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

+1我只是试图想出一个明确的方式来解释这一点,虽然OP是可能仍然会困惑。 :) –

+0

它似乎是真的没有好的方式来编码:(顺便说一句,感谢您的解释 –

+0

不客气。 – vteodor