public class HashSetText {
//1.建立一个集合hashset 向里面添加元素
//2.往hashSet集合中存储Person对象。如果姓名和年龄相同,视为同一个人。视为相同元素。 hashSet 里用hashcode equale 方法。
public static void main(String[] args) {
//定义一个HashSet 类
HashSet<Person> hs = new HashSet<Person>();
//添加元素
hs.add(new Person("lisi", 25));
hs.add(new Person("李四", 26));
hs.add(new Person("旺旺", 21));
hs.add(new Person("王五", 35));
hs.add(new Person("狗蛋", 29));
hs.add(new Person("lisi", 25));
//迭代取出
Iterator<Person> it = hs.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getName()+":"+p.getAge());
}
person类
package cn.itcast.collection;
public class Person extends Object/*implements Comparable*/ {
private String name;
private int age;
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 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;
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;
}