天天看点

HashSet重写hashCode,equals方法去除重名元素

package com.liangjing.servlet;

import java.util.HashSet;

public class SetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet set = new HashSet();

		Student s1 = new Student("s1");
		Student s2 = new Student("s1");
		set.add(s1);
		set.add(s2);

		System.out.println(set);

	}

}

class Student {
	String name;

	public Student(String name) {
		this.name = name;
	}

	public int hashCode() {
		return this.name.hashCode();
	}

	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (null != obj && obj instanceof Student) {
			Student s = (Student) obj;
			if (name.equals(s.name)) {
				return true;
			}
		}
		return false;
	}

}
           
输出 [[email protected]]