首页 > Java的Collection接口和Set接口?

Java的Collection接口和Set接口?

Java中Set接口继承自Collection接口,但两者申明的方法都一样。

问题:

1.Set继承自Collection,为什么还要把所有方法都重新申明一遍?
2.既然两个接口申明的方法都一样,为啥需要有两个接口?


iPad和iPhone,iPod touch都是来自apple,同样用iOS,但是他们确是不同的,他为什么要造几个看上去一样的东西呢?


JavaDoc 不一样,除此之外我想不到其它的原因了。


1、不一样,注释不一样。这个很重要,比如Collection对元素是否重复不限制,Set则有不重复的限制,那么同样是add方法,注释描述会有不同。
2、实现Set和Collection的实现类,约束不同,规范不同。还是上面这个问题,Set有元素不重复的限制。你把接口理解成一种规范就可以理解了。


Collection接口代表集合数据结构,Set接口只是其中一种,还有List接口了,分别代表不同的抽象,抽象的层次不同


它们外部行为一样,但潜在行为不一样。

Collection 的说明中明确说明了 Collection 是集合类似的根接口,包含一组对象,他们可能是可以重复的,也有可能不是。有些可能是排序的,有些可能不是……也就是说,它表示集合,但潜在行为并不确定。

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

而 Set 的潜在行为就确定得多,它明确了所包含的内容是不可重复的。但并没有说明排序的问题。不过它有一个 SortedSet<E> 子接口申明了内容有序。

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

所以虽然接口成员一样,但是潜在行为并不一样。当你只需要一组数据而不关系它是否重复,是否有序的时候,可以直接用 Collection 接口,但是如果你需要的是一组不可重复的数据,那显然应该用 Set 接口。


接口的内在行为不同。

【热门文章】
【热门文章】