Set集合:元素不可重复 ,并且无序存放(存放的顺序)
HashSet 只可以存放一个null值
TressSet 不可存放null值
* 1 元素重复的依据是什么
- 默认情况继承Object 走Object 的hashCode 和equals方法决定的对象的地址
- 先判断是hashCode值相同之后,在判断equals方法
- hashCode不相等,一定不是相同对象
* 2重复的时候 添加的是把之前的覆盖掉还是添加不上
- 是添加不上 ,不是覆盖
import com.java65.sort.Student;
public class Students {
int stuID;
String name;
public Students() {
}
public Students(int stuID, String name) {
this.stuID = stuID;
this.name = name;
}
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + stuID;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Students other = (Students) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (stuID != other.stuID)
return false;
return true;
}
@Override
public String toString() {
return "Students [stuID=" + stuID + ", name=" + name + "]";
}
}
public static void main(String[] args) {
HashSet<Students> hashSet =new HashSet<>();
Students stu1=new Students(1, "小乔");
Students stu2=new Students(2, "小乔");
Students stu3=new Students(1, "乔");
Students stu4=new Students(6, null);
hashSet.add(stu1);
hashSet.add(stu2);
hashSet.add(stu3);
for (Students students : hashSet) {
System.out.println(students);
}
}