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

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

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

Java代码 复制代码 收藏代码
  1. 类Parent
  2. public class Parent {
  3. // your code
  4. }
  5. 类Child
  6. public class Child extends Parent {
  7. // your code
  8. }
 类Parent
 public   class  Parent   {
  // your code 
 } 
 
类Child
 public   class  Child  extends  Parent  {
 //  your code 
 } 
 


调用的地方
Java代码 复制代码 收藏代码
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import com.test.Child;
  4. public class Test {
  5. public static void doTest(List < Parent > list) {
  6. }
  7. public static void main(String[] args) {
  8. List < Parent > parentList = new ArrayList < Parent > ();
  9. List < Child > childList = new ArrayList < Child > ();
  10. doTest(parentList);
  11. // 注意这里编译错误
  12. doTest(childList);
  13. }
  14. }
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这个函数

Java代码 复制代码 收藏代码
  1. public boolean addAll(Collection <? extends E > c) {
  2. Object[] a = c.toArray();
  3. int numNew = a.length;
  4. ensureCapacity(size + numNew); // Increments modCount
  5. System.arraycopy(a, 0 , elementData, size, numNew);
  6. size += numNew;
  7. return numNew != 0 ;
  8. }
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,明白了,这个就是问号的作用.更改我们的函数 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值