package Demo.collection;
import java.util.*;
import javax.swing.SingleSelectionModel;
public class HashSetDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet hs = new HashSet();
hs.add(new Person("lisi", 14));
hs.add(new Person("zhangsan", 17));
hs.add(new Person("zhaoliu", 19));
hs.add(new Person("lisi", 14));
hs=SingleElement(hs);
Iterator it = hs.iterator();
while (it.hasNext()) {
Person p=(Person)it.next();
System.out.println(p.getName()+p.getAge());
}
}
private static HashSet SingleElement(HashSet hs) {
// TODO Auto-generated method stub
HashSet new1=new HashSet();
Iterator it = hs.iterator();
while (it.hasNext()) {
Person obj = (Person) it.next();
if (! new1.contains(obj)) {
new1.add(obj);
}
}
return new1;
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int hashCode() {
return name.hashCode()+age;
}
public boolean equals(Object obj) {
if (!(obj instanceof Person)) {
return false;
}
Person p=(Person)obj;
return this.name.equals(p.name)&&this.age==p.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;
}
} |