且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HashTest以及对象唯一性(三)

更新时间:2022-04-01 13:42:36

package cn.cp;
//当然可以自动生成代码equals()和hashCode()方法,来确保对象的唯一性。
//这样的话存入HashTest的对象就保证了唯一性
import java.util.HashSet;
import java.util.Iterator;
class Boy3 {
	private int age;
	private String name;

	public Boy3(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public String getName() {
		return name;
	}

	@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;
		Boy3 other = (Boy3) 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 String toString() {
		return "boy3 [age=" + age + ", name=" + name + "]";
	}

}

public class HashSetTest3 {
	public static void main(String[] args) {
        Boy3 boy1=new Boy3(12, "liming");
        Boy3 boy2=new Boy3(13, "liming");
        Boy3 boy3=new Boy3(12, "liming");
        HashSet hashSet=new HashSet();
        hashSet.add(boy1);
        hashSet.add(boy2);
        hashSet.add(boy3);
        Iterator iterator=hashSet.iterator();
        while(iterator.hasNext()){
        	System.out.println(iterator.next());
        }
	}
}