JDK源码学习_JAVA数据结构和算法_集合框架_HashSet

 HashSet的remove方法的一些问题解惑:

 我们在使用HashSet删除指定元素前,如果对删除元素的属性做了修改,且修改的元素属性与其hashCode值相关,会导致元素无法删除。

 具体通过简单案例演示此问题:

创建使用到的元素对象并重写hashCode与equals方法:

Person.java

package com.dk.object.demo.hashcode;

public class Person {
	int count;

	public Person(int count) {
		this.count = count;
	}

	public String toString() {
		
		return "R[count:" + count + "]";
	}

	public boolean equals(Object obj) {
		
		if (this == obj){
			System.out.println("equals...[1]"+true);
			return true;
		}
		if (obj != null && obj.getClass() == Person.class) {
			Person r = (Person) obj;
			if (r.count == this.count) {
				System.out.println("equals...[2]"+true);
				return true;
			}
		}
		System.out.println("equals..."+obj.toString()+false);
		return false;
	}

	public int hashCode() {
		System.out.println("hashCode:"+this.count);
		return this.count;
	}
}

再编写对应的测试类,进行问题分析:

package com.dk.object.demo.hashcode;

import java.util.HashSet;

public class HashSet1 {
	
	public static void main(String[] args) {
		HashSet hs = new HashSet();
		Person p1 = new Person(-1);
		Person p2 = new Person(-2);
		hs.add(p1);
		hs.add(p2);
		System.out.println("**************【初始集合元素】*************//");
		System.out.println(hs);
		p1.count = -2;
		p2.count = -3;
		System.out.println("**************【修改后集合元素】*************//");
		System.out.println(hs);
		//移除为-2的元素
		System.out.println("**************【移除为-2的元素】*************//");
		hs.remove(p1);
		System.out.println(hs);

	}

}

运行main方法,查看最终测试结果: 

 

发布了234 篇原创文章 · 获赞 12 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/85016852