1. 程式人生 > >java 中的HashSet集合例項

java 中的HashSet集合例項

package cn;

import java.util.*;

public class Test01 {
	public static void main(String[] args) {
		HashSet set=new HashSet();
		Person p1=new Person("Jack", 23);
		Person p2=new Person("Eve", 22);
		Person p3=new Person("Jack", 21);
		set.add(p1);
		set.add(p2);
		set.add(p3);
		for(Object obj:set) {
			Person p=(Person)obj;
			System.out.println(p.name+": "+p.age);
		}
	}
}
class Person{
	String name;
	int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public int hashCode() {
		return name.hashCode();
		
	}
	public boolean equals(Object obj) {
		if (this==obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		Person other=(Person) obj;
		return other.name.equals(this.name);
	}
}