美文网首页
HashSet/TreeSet 实践

HashSet/TreeSet 实践

作者: 萌妈码码 | 来源:发表于2018-05-24 23:22 被阅读0次

    1. 作为Set元素类型的自定义类,需覆写equals, hashCode。

    Sample:自定义类Person (name, gender, age), 不覆写equals, hashCode.

    Sample Code

    hs size不变,均为1。默认hashCode基于对象引用,所以即便修改了p1属性的值,hashset仍视为同一对象。

    Override equals & hashCode之后,hs size和预期一样,每次修改之后加入,size会加1.

    Sample Code

    因为平时项目中,pojo类大部分是自动生成的(XSD生成),equals, hashCode已经默认覆写过了,所以加入set时很少考虑这个细节问题,容易出错。

    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.

    Sample Cdoe

    注意另外一个点:TreeSet中的元素should be comparable. 可以在实例化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).

    Sample Code

    结果依次打印0到99.

    4. 注意面向接口编程。声明中使用Set而不是具体实现类,以便只需要修改构造函数就可以改变具体的实现,从而影响结果。

    //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));

    相关文章

      网友评论

          本文标题:HashSet/TreeSet 实践

          本文链接:https://www.haomeiwen.com/subject/snwljftx.html