Java中如何使用泛型实现接口中的列表集合?


Java是强制实现Liskov 替换原则:

public interface Bar {
 
}
 
public interface Foo {
    Bar getBar();
}
 
public class BarImpl implements Bar {
}
 
public class FooImpl implements Foo {
    public BarImpl getBar() { ... }
}

尽管FooImpl中getter方法声明返回的是接口子类BarImpl,但一切都可以愉快地编译,因为子类可以替换基类,并且仍然符合 Liskov 替换原则。
但是,如果您尝试这样做,则会出现问题:
public interface Foo {
   List<Bar> getBars();
}
 
public class FooImpl implements Foo {
   // compiler error...
   public List<BarImpl> getBars() { ... }
}

在 Java 泛型类型系统中,List<BarImpl>不是List<Bar>. 设计这些东西的人非常聪明,可能有一个很好的技术原因。
解决:
public interface Foo<T extends Bar> {
    // we know this is "at least" a Bar
    List<T> getBars();
}
 
public class FooImpl implements Foo<BarImpl> {
   
// compiles great
    public List<BarImpl> getBars() { ... }
}

在接口中引入泛型T即可。