- package SetPackage;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashSetDemo2 {
- public static void main(String[] args)
- {
- HashSet hs = new HashSet();
- hs.add(new Person("李鸿章", 13));
- hs.add(new Person("袁世凯", 14));
- hs.add(new Person("张作霖", 15));
- hs.add(new Person("张作霖", 15));
-
- for(Iterator it = hs.iterator(); it.hasNext();)
- {
- Person obj = (Person)it.next();
- System.out.println(obj.toString());
- }
- }
- }
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public String toString()
- {
- return this.name+this.age;
- }
- public int hashCode()
- {
- System.out.println(this.name+"....Hashcode");
- return name.hashCode()+age*13;
- }
复制代码
|