HashSet

来源:互联网 发布:东风破 知乎 编辑:程序博客网 时间:2024/04/29 22:53

* –set是无序列的((=存入与存储的顺序不一定一致),元素不可以重复
* —-HashSet:底层数据结构是哈希值线程是非同步的
* 判断元素的hash值 保证元素唯一性
*
* hashCode方法和equals来完成
* 如果元素哈希值相同,才会判断equals是否为ture
* 如果元素哈希值不同,不会调用equals
*
* 注意:对于判断元素是否存在,及删除操作,依靠equals和hashCode方法
* 往hashSet集合中存入自定对象
姓名和年龄相同为同一个人,重复元素。**

package day;import java.util.HashSet;import java.util.Iterator;class Demo1{//  hashCode//  public int hashCode()返回该对象的哈希码值。支持此方法是为了提高哈希表(例如 java.util.Hashtable 提供的哈希表)的性能。     public int hashCode()    {        return 60;    }}public class hashSetD1 {public static void main(String[] args) {    System.out.println(new Demo1());//在Demo1里面覆写hashCode方法,   在hash表李里面的对象相同就顺延存放    System.out.println(new Demo1());    HashSet hashSet=new HashSet<>();    hashSet.add("k01");    hashSet.add("k01");//重复的进不去    hashSet.add("k02");    hashSet.add("k03");    hashSet.add("k04");    Iterator iterator=hashSet.iterator();    while (iterator.hasNext()) {        System.out.println(iterator.next());    }}}

练习2

package day;import java.util.HashSet;import java.util.Iterator;import javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction;class Person1{   String name;    int age;    public Person1(String a,int b) {    this.name=a;    this.age=b;}    public int hashCode()//先算哈希值再存对象    {    System.out.println(this.name+"哈希值"+this.name.hashCode());          return  this.name.hashCode()+age*23;    }    public boolean equals(Object object) {        if (!(object instanceof Person1)) {//去除非Person1类            return false;        }        //要调用子类的特有方法,必须要向下转型        Person1 aPerson1=(Person1)object;        System.out.println(this.name+" ★ equal to-"+aPerson1.name);        return this.name.equals(aPerson1.name)&&this.age==aPerson1.age;    }}public class hashSetD2 {public static void main(String[] args) {HashSet hashSet =new HashSet<>();hashSet.add(new Person1("w1", 01));hashSet.add(new Person1("w2", 21));hashSet.add(new Person1("w3", 31));System.out.println("是否存在对象"+hashSet.contains(new Person1("w3", 31)));System.out.println('\n');//先生成4个对象(哈希值)。发现比较的对象哈希值一样就调用equals方法。比较//w1=hash=3738//w2=hash=3739//w3=hash=3740//w3=hash=3740//w3 谁调用 equal to-w3//是否存在对象trueSystem.out.println("移除对象"+hashSet.remove(new Person1("w3", 31)));Iterator  iterator =hashSet.iterator();while (iterator.hasNext()) {    Person1 Person1=(Person1)(iterator.next());    System.out.println(Person1.name+"  "+Person1.age);}}}
0 0
原创粉丝点击