question_009-JAVA之Set之HashSet???

Java

Set之HashSet

HashSet 底层依赖 HashMap/

HashSet 底层依赖HashCode和equals()

------------------------------------------------


HashSet集合

A:底层数据结构是哈希表(是一个元素为链表的数组)

B:哈希表底层依赖两个方法:hashCode()和equals()

 执行顺序:

首先比较哈希值是否相同

````````相同:继续执行equals()方法

`````````````返回true:元素重复了,不添加

``````````````返回false:直接把元素添加到集合

`````````不同:就直接把元素添加到集合


------------------------------------------------


interface Collection {
...
}


interface Set extends Collection {
...
}


class HashSet implements Set {
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;

public HashSet() {
map = new HashMap<>();
}

public boolean add(E e) { //e=hello,world
        return map.put(e, PRESENT)==null;
    }
}


class HashMap implements Map {
public V put(K key, V value) { //key=e=hello,world

//看哈希表是否为空,如果空,就开辟空间
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        
        //判断对象是否为null
        if (key == null)
            return putForNullKey(value);
        
        int hash = hash(key); //和对象的hashCode()方法相关
        
        //在哈希表中查找hash值
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        //这次的e其实是第一次的world
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
                //走这里其实是没有添加元素
            }
        }


        modCount++;
        addEntry(hash, key, value, i); //把元素添加
        return null;
    }
    
    transient int hashSeed = 0;
    
    final int hash(Object k) { //k=key=e=hello,
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }


        h ^= k.hashCode(); //这里调用的是对象的hashCode()方法


        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
}

----------------------------------------------------

HashSet

保证元素的唯一性

1)依赖HashCode()

2)依赖equals()

所以,对于基本类型会自动保证唯一性,对于引用类型,必须重写hashCode()和equals()方法

······································1··············································

对于基本类型和常用引用类型,如String

package com.lys;

import java.util.HashSet;

public class HashSetDemo2 {

public static void main(String[] args) {

// 创建对象
String s1 = new String("张三");
String s2 = new String("李四");
String s3 = new String("王五");
String s4 = new String("赵六");
String s5 = new String("张三");

// 创建对象
HashSet<String> hs = new HashSet<String>();

// 添加对象
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);

for(String s: hs){
System.out.println(s+" ---  ");
}
}
}

··········结果·············

赵六 ---  
张三 ---  
李四 ---  
王五 ---  


·····································2·································

对于自定义类型,如Student类型


package com.lys;
public class Student {

private String name;
private int age;

public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}


//必须重写hashCode方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}


 // 必须重写equals方法
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) 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;
}
}

-······························································

package com.lys;

import java.util.HashSet;

public class HashSetDemo {

public static void main(String[] args) {


Student s1 = new Student("张三",12);
Student s2 = new Student("李四",22);
Student s3 = new Student("王五",32);
Student s4 = new Student("赵六",12);
Student s5 = new Student("张三",12);


HashSet<Student> hs = new HashSet<Student>();

hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);

for(Student s: hs){
System.out.println(s.getName()+" ---  " + s.getAge());
}
}
}


·················结果·······················

王五 ---  32
张三 ---  12
赵六 ---  12
李四 ---  22

············································


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值