hashset的特点:
- 无序性:元素在底层的存储位置是无序的。
- 不可重复性:hashset中的元素是不可重复的,添加相同元素时,只能添加一个。
hashset的实现原理:
- 往hashset添加元素时,hashset会先调用元素的hashcode方法得到元素的哈希值, 然后通过移位等运算就可以算出元素在哈希表中的位置,然后分为两种情况:
- 情况一:如果算出的元素存储的位置目前没有任何元素存储,那么该元素就可以直接存储到这个位置
情况二:如果算出的元素存储位置目前已经有其他的元素了那么会调用该元素的equals方法与该位置的元素在比较一次如果equals返回的是true,那么该元素与这个位置上的元素视为重复元素,不允许添加;如果返回的是false那么该元素允许添加。
实例详解
首先,创建一个Students类
package com.zzu.java13;
public class Students {
String stuNo;
String stuName;
int score;
public Students(String stuNo, String stuName, int score) {
super();
this.stuNo = stuNo;
this.stuName = stuName;
this.score = score;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Students [stuNo=" + stuNo + ", stuName=" + stuName + ", score=" + score + "]";
}
@Override
public int hashCode() {
return stuNo.hashCode();
}
@Override
public boolean equals(Object obj) {
//首先判断obj是否为空,若为空则返回false。
if(obj == null){
return false;
}else{
//若obj不为空;则判断obj是否与当前对象一样,若一样返回true。
if(this == obj){
return true;
}else{
//若不一样,则判断obj是否与当前对象属于同一种类,若属于同一种类则将obj强转为当前类。
if(obj instanceof Students){
Students stus = (Students) obj;
//最后判断obj的stuNo与当前对象的stuNo是否一样,若一样,返回true。
if(((Students) obj).getStuNo().equals(stuNo)){
return true;
}
}
}
}
return false;
}
}
然后创建一个Hashset类
package com.zzu.java13;
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set set = new HashSet();
set.add(new Students("1234","韩宇浩",59));
set.add(new Students("1234","张喜天",88));
set.add(new Students("2234","卢霖",77));
set.add(new Students("3234","王岩",89));
System.out.println(set);
}
}
输出结果为:
Students [stuNo=1234, stuName=韩宇浩, score=59]
Students [stuNo=2234, stuName=卢霖, score=77]
Students [stuNo=3234, stuName=王岩, score=89]
注意事项:
hashset中最重要的就是重写equals(),首先需要判断obj是否为空,obj为空则直接返回false,若不为空,判断obj是否与当前对象一致,一致返回true,若不一致,判断obj是否与当前对象属于同一类,是则先将obj强转为Students类,然后判断stuNo是否与当前对象一致,一致返回true,不一致返回false。