1. 程式人生 > >java中HashSet去重的方法

java中HashSet去重的方法

package day8_15;
import java.util.HashSet;
import java.util.Set;
class Employee{
	private int no ;
	private String name;
	public Employee() {
		super();
	}
	public Employee(int no, String name) {
		super();
		this.no = no;
		this.name = name;
	}
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public int hashCode() {
		//雜湊地址
		return name.hashCode()+no;
	}
	@Override
	public boolean equals(Object obj) {
		Employee e = (Employee)obj;
		return this.no==e.no&&this.name==e.name;
	}
	@Override
	public String toString() {
		return "編號:"+no+"姓名:"+name;
	}	
}
public class TestSet {
	public static void main(String[] args) {
		Set<Employee> emps = new HashSet<>();
		Employee zhangsan = new Employee(1, "張三");
		Employee lisi  = new Employee(2, "李四");
		Employee wangwu  = new Employee(1, "張三");
		emps.add(wangwu);
		emps.add(lisi);
		emps.add(zhangsan);
		emps.forEach(System.out::println);
	}
}