zoukankan      html  css  js  c++  java
  • 哈希集合——hashSet

    /**
        哈希集合特点:存取顺序不确定,同一个哈希值的位置可以存放多个元素,
                      哈希集合存放元素的时候是先判断哈希地址值:hashCode()是否相同,如果不同则直接存放;
                      如果哈希地址值相同则再调用equals()方法对元素进行判断如果元素不同则存放,如果元素相同则不存放.

                      对于判断元素是否存在依赖的是hashCode()和equals()方法

        区别:ArrayList区别元素的方法只依赖于equals();
              HashSet  区别元素的方法依赖于hashCode()和equals();
    */

    import java.util.*;
    class HashSetDemo
    {
        public static void main(String[] args)
        {
            HashSet ha=new HashSet();
            ha.add(new Person("张三",10));
            ha.add(new Person("李四",11));
            ha.add(new Person("王五",12));
            ha.add(new Person("张三",10));
            Iterator it = ha.iterator();//迭代器是哈希集合唯一的遍历方式
            while(it.hasNext())
            {
                Person p=(Person)it.next();
                sop(p.getName()+":"+p.getAge());//只有Person类中才有gerName()方法,所以必须把it.next()强制转换成Person对象
            }
        }
        public static void sop(Object obj)
        {
            System.out.println(obj);
        }
    }
    class Person
    {
        private String name;
        private int age;
        Person(String name,int age)
        {
            this.name=name;
            this.age=age;
        }
        public String getName()
        {
            return name;
        }
        public int getAge()
        {
            return age;
        }
        public boolean equals(Object obj)//此方法是在哈希集合中存贮元素的时候自动调用的 用来判断同一个哈希地址值上的对象是否相同
        {
            if(!(obj instanceof Person))//判断obj是否是Person的一个实例
                return false;
            Person p=(Person)obj;//强制吧obj转换成Person类型
            
            return this.name.equals(p.name)&&this.age==p.age;//当前对象与引用p所指引的对象判断名字与年龄是否都相同(即当前要存贮的对象与哈希集合中已有的对象做比较。)
        }
        public int hashCode()//哈希值 在存储元素的时候会自动调用接口collection中的hashCode方法,如果此方法被复写那么就自动调用复写后的方法
        {
            System.out.println(this.name.hashCode()+this.age);
            return this.name.hashCode()+this.age;
        }
        
    }

  • 相关阅读:
    观《逻辑思维,如何成为一个高手》
    第十八周 最后冲刺
    第十六周 个人项目开发流程
    个人作业
    第十四周个人总结
    排球比赛计分程序功能说明书
    Spring实战(1)
    java基础知识(三)
    JAVA中框架总结
    java基础知识(一)
  • 原文地址:https://www.cnblogs.com/james1207/p/3278049.html
Copyright © 2011-2022 走看看