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中重复添加对象的操作了

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值