亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java的Collection接口和Set接口?

Java的Collection接口和Set接口?

www說 2018-09-06 18:09:03
Java中Set接口繼承自Collection接口,但兩者申明的方法都一樣。問題:1.Set繼承自Collection,為什么還要把所有方法都重新申明一遍?2.既然兩個接口申明的方法都一樣,為啥需要有兩個接口?
查看完整描述

2 回答

?
慕神8447489

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 接口。


查看完整回答
反對 回復 2018-09-16
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

1、不一樣,注釋不一樣。這個很重要,比如Collection對元素是否重復不限制,Set則有不重復的限制,那么同樣是add方法,注釋描述會有不同。
2、實現Set和Collection的實現類,約束不同,規范不同。還是上面這個問題,Set有元素不重復的限制。你把接口理解成一種規范就可以理解了。

查看完整回答
反對 回復 2018-09-16
  • 2 回答
  • 0 關注
  • 657 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號