Problem:
If you add two identical custom student classes to the hash table, you can see the output as a two student object named Lee.
import java.util.HashSet; import java.util.Iterator; public class HashSetDemo2 {public static void Mai
N (string[] args) {//TODO auto-generated method stub hashset hshashset=new hashset ();
Hshashset.add (New Student1 ("Zhang", 22));
Hshashset.add (New Student1 ("Wang", 23));
Hshashset.add (New Student1 ("Lee", 24));
Hshashset.add (New Student1 ("Sun", 25));
Hshashset.add (New Student1 ("Lee", 24)); for (Iterator iterator = Hshashset.iterator (); Iterator.hasnext ();)
{//Iteration output System.out.println (Iterator.next ()); Class Student1//definition Student class {private String name; private int age; public Student1 (String Name,int Age) {//TODO Au
To-generated constructor Stubt This.name=name;
This.age=age;
Public String GetName () {return name.} public void SetName (String name) {this.name = name.} public int getage () {
return age; public void Setage (int age) {this.age = age;} public String toString () {return "name=" +name+ "age=" +age;}}
Obviously, the current data is not guaranteed uniqueness. The underlying hash table data structure is used to determine the position of the element by hash value, while the uniqueness of the element is ensured by the Hashcode method and the Equals method.
When the hash value is not the same, you do not need to judge the Equals method, as long as the hash value is the same to determine the Equals method.
The following is the replication, hashcode, and Equals methods in class Student1, and the output statements are added to the function to observe the order of execution
public int hashcode ()
{
System.out.println (this.name+ "... hashcode ()");
Return 1;//here returns the hash value of the object, which is generally computed, to facilitate the viewing of function execution, here I set the same hash value first.
}
public boolean equals (Object obj)
{
System.out.println (this.name+. Equals ());
Student student= (Student) obj;
Return This.name.equals (student.name) &&this.age==student.age;
}
Looks a bit messy, but if careful not difficult to find the law, when Zhang Deposit, there is no duplicate hash value, no call the Equals method, when you deposit Wang's hash value and Zhang's same, call the Equals method, and so on.
Here we modify a equals () method
public int hashcode ()
{
System.out.println (this.name+ "... hashcode ()");
Return Name.hashcode () +age*27;//by Calculation
}
You can see the following execution results
We calculate the hash value, do not repeat without calling the Equals method, as long as the hash value is the same, the Equals method is judged.
LEO 2012_5_6