妖碧落

导航

HashSet

Set 集合      基本和List 的

HashSet  set的 一个子类,由哈希表支持

  它是无序的且不能重复

  List中的add   返回值一直是true          Set  不可以存重复

HashSet存储自定义对象,保证元素唯一性(属性):
  HashSet在调用add()的时候 会先调用对象的hashcode()
  重写自定义对象的hashCode() 及equals()
  重写hashcode() ,根据对象属性返回值,如果不重写,则hashcode 肯定不一样那么就可以存属性相同的对象了
  重写equals(), hashcode一样,则开始调用equals() 继续比较

  官方的重写方法如下:

@Override
    public int hashCode() {
        final int prime = 31;  
        /*
         * 为什么是31?
         * 1、31是一个质数
         *    没有公约数
         * 2、31既不大也不小   太大了可能超过int的取值方位
         * 3、31 好计算   2的55次方减一   2向左移动5位
         */
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        // 健壮性
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

 

 

 LinkedHashSet是唯一一个保证怎么存就怎么取得Set集合

  底层是链表实现的

 

去掉List 中的重复元素:

  ①、hs.addAll(list)      ② list.clear()          ③ 迭代 将 HashSet添加回 list

 

posted on 2019-08-05 22:26  妖碧落  阅读(149)  评论(0编辑  收藏  举报