您的位置:首页 > 其它

将自定义对象存入到HashSet集合中并去除重复元素

2014-07-19 20:51 591 查看
|--HashSet:底层数据结构是哈希表。是线程不安全的。不同步。

HashSet是如何保证元素唯一性的呢?

是通过元素的两个方法,hashCode和equals来完成。

如果元素的HashCode值相同,才会判断equals是否为true。

如果元素的hashcode值不同,不会调用equals。

注意,对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。

//HashSet加入的对象需要重写hashCode方法和equals方法,因为对于自定义类需要提供判断怎样才算重复元素的方法。

//本例中的hashCode方法和equals方法即是用来判断student对象是否为重复对象的标准方法。

package tan;
import java.util.HashSet;
import java.util.Iterator;
 class Student{
	private int age;
	private String name;
	public Student(int age, String name) {
		this.age = age;
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "name:"+name+"age:"+age;
	}
	
	//HashSet加入的对象需要重写hashCode方法和equals方法,因为对于自定义类需要提供判断怎样才算重复元素的方法。
	//本例中的hashCode方法和equals方法即是用来判断student对象是否为重复对象的标准方法。
	@Override
	public int hashCode() {
		System.out.println(this.name+"....hashCode");
		return name.hashCode()+age*25;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(!(obj instanceof Student)){
			return false;
		}
		Student student=(Student)obj;
		System.out.println(this.name+"...equals...."+student.name);
		return this.name.equals(student.name)&& this.age==age;
	}
}
public class HashSetTest {
	public static void main(String[] args) {
		HashSet hs=new HashSet();
				
				hs.add(new Student(20,"tan1"));
				hs.add(new Student(21,"tan2"));
				hs.add(new Student(22,"tan3"));
//				hs.add(new Student(20,"tan1"));
				hs.add(null);//HashSet中可以添加null值
			
			System.out.println(hs.contains(new Student(21, "tan2")));	
				//删除元素
				hs.remove(new Student(21, "tan2"));
				
				
				Iterator it=hs.iterator();
				while(it.hasNext()){
					Object obj=it.next();
					if(obj==null){
						System.out.println(obj);
						continue;
					}else{
						Student s=(Student)obj;
						System.out.println("name:"+s.getName()+" "+"age:"+s.getAge());
					}
					
					
				}
	}
}
结果为:

tan1....hashCode

tan2....hashCode

tan3....hashCode

tan2....hashCode

tan2...equals....tan2

true

tan2....hashCode

tan2...equals....tan2

null

name:tan1 age:20

name:tan3 age:22
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐