HashSet保证存储元素内容不重复的执行原理

HashSet保证存储元素内容不重复的执行原理:

通过 set.add(s1)将对象存储HashSet集合中时,默认 调用 存储对 象(s1)的 hashCode方法,获取哈希码值,哈希码值通过一 定计算(哈希值%底层数组长度)得到存储位置下标,如果此下 标上没有存储过任何元素,则 直接存储;但是存储该下标上已经存储对应的元素,此时默认调用 s1对象对应类中的 equals方法判断存储对象和 此下标已经对象的内容是否相 同,如果 equals结果为true,代表内容相同对象,则s1被拒 绝添加到集合中;但是如果equals结果为 false代表内容不 同的对象,则s1允许添加到集合中,也是存储在此下标中, 这时采用是数组+链表形式进行存储。

public class Student {
private String name;
private Integer age;
private Double score;
public Student() {
super();
}
public Student(String name, Integer age,Doublescore) {
super();
this.name = name;
this.age = age;
this.score = score;
    }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ",age=" + age 
    +", score=" + score + "]";
}
@Override
public int hashCode() {
final int prime = 31;
    int result = 1;
result = prime * result + ((age ==
null) ? 0 :
age.hashCode());
result = prime * result + ((name ==
null) ? 0 :
name.hashCode());
result = prime * result + ((score ==
null) ? 0 :
score.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("---equals----");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
    } else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (score == null) {
if (other.score != null)
return false;
} else if (!score.equals(other.score))
return false;
return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值