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