HashSet – 覆盖equals, hashCode

Categories: Java; Tagged with: ; @ January 28th, 2009 17:57

覆盖equlas 和hashCode两函数, 获得更自由的控制.

某set, 存一些Email, 如下:
[email protected] 
[email protected]
[email protected]
[email protected]
[email protected]

很明显, 一共3个不同邮箱,

现在创建了Email类, 需要将这帮Email放入一个HashSet中, 当然,

[email protected]
[email protected]
[email protected]
[email protected]
这几个是一模一样的, 都是[email protected]

因此需要重写Email的equlas 和hashCode两个函数, 以便保证Set的唯一性.

代码:

	//重写equals
	public boolean equals(Object obj) {
		if(this == obj) {
			return true;
		}
		
		final Email email = (Email)obj;
		
		if(this.pB.equals(email.pB) && this.pA.equalsIgnoreCase(email.pA)) {
			return true;
		}else {
			return false;
		}
	}
	
	//重写hashCode
	public int hashCode() {
		int result;
		result = pB.hashCode() + pA.toLowerCase().hashCode();
		return result;
	}

在Email外部将这开始提到的这帮email建立为Email类, 并加入到某Set中,

注意: 为了保证HashSet正常工作, 要求当两个对象用equals()方法比较结果为True时, 起hashCode也必须相同, 因此覆盖了equals之后 必须覆盖hashCode.

结果是该Set的size为3 – 达到要求….



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.