`
codsoul
  • 浏览: 209017 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

(转)JDK泛型中的问号(?)的用途 (泛型集合类的作为参数的时候的继承问题)

阅读更多
(转)http://www.blogjava.net/dreamstone/archive/2007/02/10/99195.html

Jdk1.5中支持了泛型,在泛型的使用过程中经常会遇到这样一类问题

 类Parent
 public   class  Parent   {
  // your code 
 } 
 
类Child
 public   class  Child  extends  Parent  {
 //  your code 
 } 
 


调用的地方
import  java.util.ArrayList;
 import  java.util.List;

 import  com.test.Child;


 public   class  Test   {
     public   static   void  doTest(List < Parent >  list)  {
        
    } 
      public   static   void  main(String[] args)  {
        List < Parent >  parentList  =   new  ArrayList < Parent > ();
        List < Child >  childList  =   new  ArrayList < Child > ();
        doTest(parentList);
         // 注意这里编译错误 
         doTest(childList);
        
    } 
} 


你会发现编译错误,但是在我们的需求中Child的集合类是可以代替Parent的集合类来使用的,但是因为编译器不认同,因为两个集合类之间没有直接的继承关系。如果实现呢?在Jdk1.5的Source中我们找到了答案,随便找一个带有泛型的类,点进去可以看到泛型的定义,例如ArrayList<E>  HashMap<K,V>  等等
这里以ArrayList为例:注意addAll这个函数

public   boolean  addAll(Collection <?   extends  E >  c)   {
    Object[] a  =  c.toArray();
         int  numNew  =  a.length;
    ensureCapacity(size  +  numNew);   //  Increments modCount 
         System.arraycopy(a,  0 , elementData, size, numNew);
        size  +=  numNew;
     return  numNew  !=   0 ;
    } 



ok,明白了,这个就是问号的作用.更改我们的函数
import  java.util.ArrayList;
 import  java.util.List;

 public   class  Test   {
         // 这里更改一下,利用问号解决问题  
       public   static   void  doTest(List <?   extends  Parent >  list)  {
        
    } 
      public   static   void  main(String[] args)  {
        List < Parent >  parentList  =   new  ArrayList < Parent > ();
        List < Child >  childList  =   new  ArrayList < Child > ();
        doTest(parentList);
         // 注意这里编译正确        
         doTest(childList)    } 
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics