Set类集合的特点
Set类集合的特点:
1.无序
2.唯一
3.只能存储一个null值
Set<String> set=new HashSet();
set.add(null);
set.add(null);
set.add("cv");
set.add("we");
set.add("cv");
打印结果:[null, cv, we]
HashSet
特点:
无序
唯一
只能有一个null值
问题:
- 1.HashSet是如何保证元素唯一的?
hashCode equals - 2.HashSet是如何导致元素无序?
元素存储到哈希表结构当中是通过 对象的hashCode经过某种运算产生的相对不确定的数 - 3.HashSet为什么和存储不一样,却每次遍历的顺序都一样?
因为每次遍历的时候是同一个对象,同一个对象产生的哈希值是一样的
使用set添加对象时,为什么要重写hashcode方法?
因为对象在生成的时候,会随机生成不同的hashcode值,
但hashcode方法是根据对象的内容生成的值,重写hashcode方法以后,相同内容则hash值相同
其实最主要是为了满足Set集合的add机制,因为add转集合的put,该方法要比较hash 和equals
public class Set_02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Student> sr=new HashSet();
sr.add(new Student("ljx",89.5));
sr.add(new Student("ljx",89.5));
sr.add(new Student("ljx1",87.5));
sr.add(new Student("ljx",89.5));
System.out.println(sr);
}
}
class Student{
String name;
Double Score;
@Override
public String toString() {
return "Student [name=" + name + ", Score=" + Score + "]";
}
public Student(String name, Double score) {
super();
this.name = name;
Score = score;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((Score == null) ? 0 : Score.hashCode());
result = prime * result + ((name == null) ? 0 : name.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 (Score == null) {
if (other.Score != null)
return false;
} else if (!Score.equals(other.Score))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}