Chan Chen Coding...

Question Mark ? in Java


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


 import  java.util.List;
 import  com.test.Child;
 import  java.util.ArrayList;

 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);
         // Compile Error 
         doTest(childList);
    } 

See addAll Method in ArrayList

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


Modify Our Code
 import  java.util.ArrayList;
 import  java.util.List;


 public   class  Test  {
         // Change Our Method at Here
      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);
          // Compile Correct    
         doTest(childList) 
     } 


-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;

posted on 2012-11-23 15:47 Chan Chen 阅读(250) 评论(0)  编辑  收藏 所属分类: Scala / Java


只有注册用户登录后才能发表评论。


网站导航: