最近在学习Java集合框架源码,在看到List接口时发现虽然List接口继承自Collection接口,但是Collection接口中一些已定义的抽象方法(例如:size(),isEmpty()等)在List接口中却又重新定义了一次,为什么这么做呢?答案在List接口描述中已经给了,我们可以在List接口描述中看到如下描述:
The List interface places additional stipulations, beyond those specified in the
Collection interface, on the contracts of the iterator, add, remove, equals, and
hashCode methods. Declarations for other inherited methods are also included here for
convenience.
翻译:
List接口在Collection接口指定的约束之外,在iterator、add、remove、equals和hashCode方法上添加了其他的约定。为了方便起见,还包含了其他继承方法的声明。
我们可以看到,之所以在List接口中重新定义一次,主要是为了方便(for convenience),不然总要往上一层层去父类中找,就会很繁琐。