重写equals和hashCode方法,让入HashSet中的内容不重复

阅读更多

 

package com.zj.hashset.test;

import java.util.HashSet;

/**
 * 功能:重写equals和hashCode方法,让相同姓名的用户不能重复加入HashSet
 * @author zhengjiong
 * time:2011-9-14 下午11:52:44
 */
public class HashSet_Test {
	
	public static void main(String[] args) {
		
		People p1 = new People("zhangsan");
		People p2 = new People("zhangsan");
		
		System.out.println(p1.hashCode());
		System.out.println(p2.hashCode());
		
		HashSet set = new HashSet();
		set.add(p1);//HashSet会自动调用hashcode方法,List不会
		set.add(p2);
		
		System.out.println(set);
		
	}
}
class People {
	String name;
	
	public People(String name){
		this.name = name;
	}
	
	@Override
	public int hashCode() {
		return this.name.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj){
			return true;
		}
		if(obj != null)
		{
			if(obj instanceof People){
				return this.name.equals(((People)obj).name) ? true : false;
			}
		}
		return false;
	}
}

你可能感兴趣的:(java,HashSet)