zoukankan      html  css  js  c++  java
  • HashSet

    1、无序、不可重复。

    2、实现原理:当执行添加元素的时候,先调用hashCode()方法,得到哈希值,然后根据此值去哈希表找到相应的存储位置。

      (1)位置空:则直接存储。

      (2)位置不空:则调用equals()方法,如果equals()返回true,则视为同意元素,不在加入;否则加入。(一个位置可以存放多个不同的元素)

    package cd.itcast.runble;
    
    import java.util.HashSet;
    
    class Person{
        int id;
        String name;
        public Person(int id, String name) {
            this.id = id;
            this.name = name;
        }
        @Override
        public String toString() {
            return "{编号:"+this.id+" 姓名:"+this.name+"}";
        }
        @Override
        public int hashCode() {
            return this.id;
        }
        @Override
        public boolean equals(Object obj){
            Person person=(Person)obj;
            return this.id==person.id;
        }
        
    }
    public class Demo3 {
        public static void main(String[] args) {
            HashSet set = new HashSet();
            set.add(new Person(110, "狗娃0"));
            set.add(new Person(111, "狗哇1"));
            set.add(new Person(112, "狗娃2"));
            set.add(new Person(110, "狗娃0"));//此元素不能再加入,需要重写hashcode(),equals()
            System.out.println("集合的个数是:"+set.size());
            System.out.println("集合的元素是:"+set);
        }
    }

    3、

    package cd.itcast.runble;
    
    public class Demo4 {
        public static void main(String[] args) {
            String str1 = "hello";
            String str2 = new String("hello");
            //false,原因hashCode()默认情况下是内存地址,但是此时String类重写了Object的hashCode()
            System.out.println("str1是否等于str2:"+str1==str2);
            System.out.println("str1:"+str1.hashCode());
            System.out.println("str2:"+str2.hashCode());
        }
    }
  • 相关阅读:
    (转) 理解Angular中的$apply()以及$digest()
    Gulp 有用的地址
    AngularJS中Directive指令系列
    让博客园博客中的图片支持fancybox浏览
    Drupal7 实现like(点赞)功能
    Drupal7 针对特定条件才显示区块
    Windows server 2008 tomcat间歇性掉线关闭
    关于tomcat8在windows2008下高并发下有关问题的解决方案
    combotree 的简单使用2
    @responseBody 返回更多数据
  • 原文地址:https://www.cnblogs.com/h-g-f-s123/p/6047211.html
Copyright © 2011-2022 走看看