HashSet添加对象出现重复情况

HashSet添加对象出现重复情况

package HashCode;
import static org.junit.Assert.*;
import java.util.HashSet;
public class Test {

	@org.junit.Test
	public void test() {
		HashSet<Student> hashSet = new HashSet<Student>();
		Student student1 = new Student("wjw", "男", 12);
		Student student2 = new Student("wjw", "男", 12);
		Student student3 = new Student("wjw3", "男", 14);
		hashSet.add(student1);
		hashSet.add(student2);
		hashSet.add(student3);
		for (Student student : hashSet) {
			System.out.println(student);
		}
	}
}

在测试类中打印的数据是可以重复的,这个就违背了HashSet中的元素不可重复的原则。

Student [name=wjw, sex=, age=12]
Student [name=wjw3, sex=, age=14]
Student [name=wjw, sex=, age=12]

所以我们在写对象的时候注意重写HashCode方法和equals方法

package HashCode;
public class Student {
	private String name;
	private String sex;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}
	public Student(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		return true;
	}
}

	

然后进行添加的操作就可以防止向HashSet中重复添加对象的操作了

你可能感兴趣的:(java)