2 回答

TA貢獻1780條經驗 獲得超1個贊
它們外部行為一樣,但潛在行為不一樣。
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 接口。

TA貢獻1735條經驗 獲得超5個贊
1、不一樣,注釋不一樣。這個很重要,比如Collection對元素是否重復不限制,Set則有不重復的限制,那么同樣是add方法,注釋描述會有不同。
2、實現Set和Collection的實現類,約束不同,規范不同。還是上面這個問題,Set有元素不重復的限制。你把接口理解成一種規范就可以理解了。
添加回答
舉報