考虑以下类:
interface Notifiable {
}
class NotifiableImpl1 implements Notifiable {
}
class NotifiableImpl2 implements Notifiable {
}
class NotifiableImpl3 implements Notifiable {
}
以下代码正常工作:
Set<Notifiable> set = new HashSet<>();
set.add(new NotifiableImpl1());
set.add(new NotifiableImpl2());
set.add(new NotifiableImpl3());
但是,以下代码不起作用:
Set<? extends Notifiable> set2 = new HashSet<>();
set2.add(new NotifiableImpl1());
set2.add(new NotifiableImpl2());
set2.add(new NotifiableImpl3());
我知道它不起作用,因为它应该只能添加 to的一个具体子类型,但是它是怎么来的,下面的代码也不起作用?Notifiable
set2
Set<? extends Notifiable> set2 = new HashSet<>();
set2.add(new NotifiableImpl1());
也许更有趣的是,为什么以下工作?
Set<Notifiable> set = new HashSet<>();
set.add(new NotifiableImpl1());
set.add(new NotifiableImpl2());
set.add(new NotifiableImpl3());
Set<? extends Notifiable> set3 = set;