close

Set是一種Collection的實作介面, 主要常見的有三種實作
HashSet, TreeSet和LinkedHashSet

Set的特性是不收集重復的元素
當元素是物件時, 需要實作hashCode和equals方法
才不會達不到想要的結果
其中null也可以當作元素加入


HashSet
官網: https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
就是雜湊的實踐, 物件會存入一個個的Hash bucket
然後利用雜湊碼來取得與判斷物件
內部元素沒有順序性
無法用get來取得
只能一步步拜訪
一些概念可以參考資料結構
或者是林老師的網頁https://openhome.cc/Gossip/Java/Set.html

LinkedHashSet
官網: https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html
LinkedHashSet繼承HashSet
然後使其內部元素有順序性
一樣沒有get方法
要注意的是其不是synchronized
如果要實踐同步必需在外部實行
ex:
Set s = Collections.synchronizedSet(new LinkedHashSet(...));

TreeSet:
官網: https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
有Set的特性, 但是他會將元素由小到大排序
和HashSet一樣無法用get來取得特定的元素
但是有提供一些方法來取得內部的元素
可參考http://wiki.jikexueyuan.com/project/java-enhancement/java-twentyeight.html
其中排序方法如果要自訂
則需要實作Comparator
可參考https://openhome.cc/Gossip/JavaGossip-V2/TreeSet.htm

 

1. 官網https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html

01.png  

arrow
arrow
    文章標籤
    Java Set
    全站熱搜

    RX1226 發表在 痞客邦 留言(0) 人氣()