网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 知识问答

java中的Set集合HashSet集合

时间:2026-02-12 10:46:34

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

可见唯一!

© 2026 阿力知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com