a- package setdemo;
- import java.util.HashSet;
- /**
- * 需求:存储自定义对象,并保证元素的唯一性
- * 要求:当对象的成员变量值都相同,则认为是一个元素
- */
- public class HashSetDemo1 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //创建哈希set存储对象
- HashSet<Student> hs = new HashSet<Student>();
- //创建学生对象
- Student s1 = new Student("Lili", 15);
- Student s2 = new Student("Lucy", 15);
- Student s3 = new Student("Lala", 8);
- Student s4 = new Student("Lili", 17);
- Student s5 = new Student("Cici", 15);
- Student s6 = new Student("Lili", 15);
- //添加对象到集合
- System.out.println("添加对象:"+hs.add(s1));
- System.out.println("添加对象:"+hs.add(s2));
- System.out.println("添加对象:"+hs.add(s3));
- System.out.println("添加对象:"+hs.add(s4));
- System.out.println("添加对象:"+hs.add(s5));
- System.out.println("添加对象:"+hs.add(s6));
- //遍历输出对象
- for (Student s : hs) {
- System.out.println(s.getName()+"..."+s.getAge()+"...hashCode:\t"+s.hashCode());
- }
- }
- }
复制代码- package setdemo;
- public class Student {
- private String name;
- private int age;
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- //重写hashCode()和toString()方法
- @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;
- }
-
- }
复制代码
|
|