public class demo1_Hashset {
/*
* 存储自定义对象保证元素的唯一性
*/
public static void main(String[] args) {
HashSet<Person> hs = new HashSet<>(); //创建HashSet对象
hs.add(new Person("张三",23));
hs.add(new Person("张三",23));
hs.add(new Person("李四",24));
hs.add(new Person("李四",24));
hs.add(new Person("王五",25));
hs.add(new Person("王五",25));
for(Person p : hs){ //曾强for循环遍历
System.out.println(p);
}
//System.out.println(hs);
}
}
package com.heima.hashset;
public class Person implements Comparable<Person>{
public String name; //姓名
public int age; //年龄
public Person() { //空参构造
super();
}
public Person(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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]"; //重写toString()方法
}
@Override
public int hashCode() { //重写hasgCode()方法
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) { //重写equals()方法
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) 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;
}
@Override
public int compareTo(Person o) { //重写compareTo()方法