一個最好的詮釋hashcode的作用的例子

瓜瓜東西發表於2014-04-09
import java.util.*;

public class HashCode {
	public static void main(String[] args) {
		Collection c = new HashSet();
		c.add("hello");
		c.add(new Name("f1", "l1"));
		c.add(new Integer(100));
		c.remove("hello");
		c.remove(new Integer(100));
		System.out.println(c.remove(new Name("f1", "l1")));
		System.out.println(c);
		
		System.out.println("abc".hashCode());
		System.out.println("abc".hashCode());
	}
}

class Name {
	private String firstName, lastName;

	public Name(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String toString() {
		return firstName + "-" + lastName;
	}

	public boolean equals(Object obj) {
		if (obj instanceof Name) {
			Name name = (Name) obj;
			return (firstName.equals(name.firstName))
					&& (lastName.equals(name.lastName));
		}
		return super.equals(obj);
	}

	public int hashCode() {
		System.out.println("--"+lastName.hashCode());
		return lastName.hashCode();
	}
}


--3397
--3397
true
[]
96354
96354




相關文章