java学习-HashSet 添加引用类型 的 内容去重原理,究其原码
发布日期:2021-05-07 10:13:26 浏览次数:34 分类:精选文章

本文共 4343 字,大约阅读时间需要 14 分钟。

去重方法

HashSet去重需要重写 hashCode和equals方法,这两个方法继承自Object类。

例如创建如下Student类

class Student{   	String name;	public Student(String name) {   		super();		this.name = name;	}	@Override	public int hashCode() {   		final int prime = 31;		int result = 1;		result = prime * result + ((name == null) ? 0 : name.hashCode());		return result;	}	@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 (name == null) {   			if (other.name != null)				return false;		} else if (!name.equals(other.name))			return false;		return true;	}}

主函数添加两个同内容的Student对象

public class Test {   	public static void main(String[] args) throws IOException, InterruptedException {   		HashSet
set = new HashSet
(); set.add(new Student("张三")); set.add(new Student("张三")); }}

原理

我们点击add方法进去,查看其原码

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

E是泛型,例如上面的代码中HashSet,这里就将Student类型传进去,也就是说E就代表Student。

这里的PRESENT是

private static final Object PRESENT = new Object();

这里的map是

private transient HashMap
map;

由此可见,Hashset,其实际上是使用HashMap实现的,Hashset中一直维护了一个HashMap的实例。

add方法实际是调用的HashMap的put方法,这里利用了HashMap的键不能重复的原理。
放入的键是 传入的Student类型的实例,放入的值是PRESENT,实际上是一个Object的实例,这里用了final,因而是一个常量,即每个键值对的值相同。

再看键为什么不会重复。

查看此put方法
传入的5个变量分别是 :

  1. key的哈希值(即student的哈希值)这里调用的是key.hashCode()即student里重写的hashCode(),这也是为什么必须要重写hashCode的原因
  2. 键值 即student对象的引用
  3. 值value 即都相同的object对象
  4. false
  5. true
public V put(K key, V value) {           return putVal(hash(key), key, value, false, true);    }static final int hash(Object key) {           int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}

这个方法的返回值又调用了一个putVal方法,我们查看其源代码

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {           Node
[] tab; Node
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
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
)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; }

看起来很乱,但我们只需要看其中一小部分就够了,其他的无非是排除异常,初始赋值,哈希表配置,等操作

重点看这两行

if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))                        break;

这里的e可以当成一个对 map中的键的遍历,实际是一个链表,通过.next找下一个值,所以这里没有循环的结构,如果不懂数据结构的话,可以先当成一个map中的键的遍历,即每次e都代表一个student对象的引用,这些student对象是 存储在 map中的键

e.hash即获取一个student对象的哈希值

  • e.hash == hash就是新传入的对象的哈希值 和 以前传入的对象的哈希值 是否相等。这里有一个短路效应,当哈希值不同时,返回false 则 &&后的的不会再比较,如果不重写hashcode(),那么内容相同的对象,返回的哈希值是不同的,这里就会一直是false,就不会实现去重
  • (k = e.key) == key,这里是比较的地址,确定这两个引用指向的对象地址是否相同
  • (key != null && key.equals(k))这里才是比较的equals方法,key.equals(k),就是调用的student类中的equals方法。如果没重写,则调用object中的equals方法,其比较的仅仅是地址是否相同,因此必须重写equals方法才能实现内容去重

在这里再贴一下object类中的hashcode和equals方法

public native int hashCode();public boolean equals(Object obj) {           return (this == obj);    }

ps:这里说一下native,这是一个修饰符,java关键字,其修饰的方法实现是用其他语言实现的,通常是c++。方法实现在其他语言的编译文件内。

由此可以了解,内容去重,要重写hashCode和equals方法

上一篇:java-典型的死锁问题
下一篇:java学习-线程的6种状态,究其原码

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年03月31日 17时43分26秒