java中的Set集合HashSet集合
1、public class HashSetDemo {
public static void main(String[] args) {
//创建集合
HashSet<Student> hash = new HashSet<Student>();
//创建学生对对象
Student s1 = new Student("one",1);
Student s2 = new Student("two",2);
Student s3 = new Student("two",2);
Student s4 = new Student("three",3);
Student s5 = new Student("four",4);
Student s6 = new Student("four",4);
Student s7 = new Student("five",5);
//添加
hash.add(s1);
hash.add(s2);
hash.add(s3);
hash.add(s4);
hash.add(s5);
hash.add(s6);
hash.add(s7);
//遍历
for(Student s : hash)
{
System.out.println(s.getAge() + s.getName());
//不是说唯一性吗?为什么打印出来发现相同的元素还是有的呢?
//原因是因为低沉用hashcode和equals方法进行比较的
//而对象却没有重写父类Object的hashcode和equals方法!所以当然不同了!
}
}
}
2、所以在学生对象要重写equals和Hashcode方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
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 (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
3、打印输出:
3three
4four
1one
2two
5five
可见唯一!