1.?作為Set元素類型的自定義類,需覆寫equals, hashCode假瞬。
Sample:自定義類Person (name, gender, age), 不覆寫equals, hashCode.
hs size不變岭参,均為1。默認(rèn)hashCode基于對象引用,所以即便修改了p1屬性的值能岩,hashset仍視為同一對象募强。
Override equals & hashCode之后株灸,hs size和預(yù)期一樣崇摄,每次修改之后加入,size會加1.
因?yàn)槠綍r項(xiàng)目中慌烧,pojo類大部分是自動生成的(XSD生成)配猫,equals, hashCode已經(jīng)默認(rèn)覆寫過了,所以加入set時很少考慮這個細(xì)節(jié)問題杏死,容易出錯泵肄。
2. Set?also adds a stronger contract on the behavior of the?equals?and?hashCode?operations, allowing?Set?instances to be compared meaningfully even if their implementation types differ. Two?Set?instances are equal if they contain the same elements.
兩個Set包含相同的元素,則equals為true.
注意另外一個點(diǎn):TreeSet中的元素should be comparable. 可以在實(shí)例化TreeSet的時候指定一個Comparator.
3.??LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).
結(jié)果依次打印0到99.
4. 注意面向接口編程淑翼。聲明中使用Set而不是具體實(shí)現(xiàn)類腐巢,以便只需要修改構(gòu)造函數(shù)就可以改變具體的實(shí)現(xiàn),從而影響結(jié)果玄括。
//conversion constructor
Collection noDups = new HashSet(c);//去重
???????Collection noDups = new LinkedHashSet(c);//去重冯丙,保留原序
??????//aggregate operations
??????c.stream().collect(Collectors.toSet()); // no duplicates
??????Set set = people.stream().map(Person::getName)
????????????????????????.collect(Collectors.toCollection(TreeSet::new));