zoukankan      html  css  js  c++  java
  • 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

    竹杖芒鞋轻胜马,一蓑烟雨任平生。 回首向来萧瑟处,也无风雨也无晴。
  • 相关阅读:
    win10 uwp 模拟网页输入
    PHP prev() 函数
    PHP pos() 函数
    PHP next() 函数
    PHP natsort() 函数
    PHP natcasesort() 函数
    virtualenv
    自古枪兵幸运E
    win10 uwp DataContext
    win10 uwp DataContext
  • 原文地址:https://www.cnblogs.com/yaobiluo/p/11305994.html
Copyright © 2011-2022 走看看