详述HashSet类add方法(四)

在自定义类中重写hashCode方法

public class Student {
    private String id;
    
    public Student(String id) {    
        this.id=id;
    }

    @Override
    public int hashCode() {
        return id.hashCode();//返回id的hash值
    }
}

 

import java.util.HashSet;

public class Test1 {

    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<Student>();
        System.out.println(set.add(new Student("100")));//true
        System.out.println(set.add(new Student("100")));//true
    }

}

 HashSet中add方法

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

 HashMap中put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

HashMap中putVal方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)               //第二次添加时执行Student中的hashCode方法,返回值相同
            tab[i] = newNode(hash, key, value, null);      //不执行
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//equals方法未重写,equals方法返回值为false
                e = p;                                                                        //不执行
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;//返回null
    }

putVal方法返回null

put方法返回null

add方法返回true,添加成功

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值