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;