Java中详述HashSet类add方法(五)

new 对象(“数据内容”)数据重复(三)

通过(一)(二)部分我们可以发现,尽管两次new 对象(“数据内容”)的hashCode值相同,但是仍能存储重复的数据,对equals方法进行重写,看看结果是否会发生改变:

package sun;

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")));
		System.out.println(set.add(new Student("100")));
		System.out.println(new Student("100").hashCode());
		System.out.println(new Student("100").hashCode());
	}
}
结果为:
true
false
48625
48625
package sun;

public class Student {
	
	private String id;
	
	public Student(String id) {
		this.id = id;
	}
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Student) {
			Student stu = (Student) obj;
			return this.id.equals(stu.id);
		}
		return false;
	}	
}

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);

其调用的hash方法调用的hashCode方法(调用Object类中的hashCode方法)为:

static final int hash(Object key) {
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

因为前后两次存储数据时的hashCode相同,所以hash(key)的值也相同。

HashMap 中的putVal方法:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

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)
            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))))
                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)// onlyIfAbsent本来就为false,所以!onlyIfAbsent true
                    e.value = value;
                afterNodeAccess(e);
                return oldValue; 
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

摘录除每一步代码进行分析:

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;

由于存第一个对象时,全局变量table已经被赋值,所以tab=table不为空,即不等于null。而且n=tab.length=16!=0,因此,if的判断结果为false,进入下一个判断语句。

  		if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
  		else {
        	……
        }

i = (n - 1) & hash = 数组长度-1 & hash值,即16-1 & hash,因为第一个和第二个值的hashCode相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是相等的 ,所以存第二个对象时,tab[i = (n - 1) & hash]不为null,进入else中的if语句:

			Node<K,V> e; K k;
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

p.hash(第一个学生id hash的值等于第二个学生id的hash值),所以p.hash= =hash判定为true,而(k = p.key) == key因为p.key为第一次存储时学生id的key,与第二次待存储的学生id的key不同,所以判定为false,又因为key不为null判定为true,且key.equals(k)调用的equals方法为重写后的equals方法,返回值为true,因此判断语句整体结果为true,执行将p的值赋给e的操作后,执行下列操作:

			if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)// onlyIfAbsent本来就为false,所以!onlyIfAbsent true
                    e.value = value;
                afterNodeAccess(e);
                return oldValue; 
            }

e=p!=null,因此if判断语句成立,执行将e.value赋给V oldValue,因为onlyIfAbsent被赋初值为false,因此!onlyIfAbsent为true,将e.value的值赋给value(待存储的value值),返回oldValue值。

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

putVal方法得到的返回值为oldValue值,因此返回oldValue值至上一级put方法;

	public boolean add(E e) {//E e为输入的"wjq"
        return map.put(e, PRESENT)==null;
	}

HashMap的put方法得到的返回值为oldValue值,return map.put(e, PRESENT)==null; 语句不成立,结果为false,因此,返回值为false,重复的数据存储失败。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值