第九:hashCodeとequals方法の実現メカニズム

2582 ワード

一.
注意hashCodeとequals法のHashSetにおける応用(HashSetTest 3)
public class HashSetTest {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Set set =new HashSet();//Set  collection
		set.add("zhangsan");
		set.add("lisi");
		set.add("wangwu");
		System.out.println(set.add("zhangsan"));// ... !
		System.out.println(set.size());//Set 
	}
}
// hashCode equals 
public class HashSetTest2 {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Set set = new HashSet();

		People p1 = new People("zhangsan");
		People p2 = new People("lisi");
		People p3 = new People("wangwu");
		People p4 = new People("zhangsan");
		People p5 = new People("zhangsan");

		set.add(p1);
		set.add(p2);
		set.add(p3);
		set.add(p4);
		set.add(p5);
		System.out.println(set.size());
	}
}

class People {
	String name;

	public People(String name) {
		this.name = name;
	}
}
// hashCode equals 
public class HashSetTest3 {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Set set =new HashSet();
		
		Student p1=new Student("zhangsan");
		Student p2=new Student("lisi");
		Student p3=new Student("wangwu");
		Student p4=new Student("zhangsan");
		Student p5=new Student("zhangsan");
		
		set.add(p1);
		set.add(p2);
		set.add(p3);
		set.add(p4);
		set.add(p5);
		System.out.println(set.size());
	}
}

class Student{
	String name;
	public Student(String name){
		this.name=name;
	}
	// 
	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		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;
		final Student other = (Student) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	

	/*// 
	@Override
	public int hashCode() {
		System.out.println("hashCode executed!");
		return name.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		System.out.println("equals executed!");
		if (this == obj) {
			return true;
		}
		if (obj instanceof Student) {
			Student s = (Student) obj;
			return name.equals(s.name);
		}
		return false;
	}*/
	
}