If you are lazy and do not set equals (), it will result in the return hashcode, although the result is the same, but the execution of the program will call equals () multiple times, thus affecting the efficiency of program execution.
We want to ensure that the return of the same object hashcode must be the same, but also to ensure that the hashcode of the same object is as different as possible (because the bounds of the array, hashcode may be the same). Example:
public int hashcode () {
Return Name.hashcode () +age;
}
This example ensures that the same name and age record returned by the hashcode are the same.
Advantages of using HashSet:
The bottom of the hashset is an array, and its query efficiency is very high. Moreover, when adding and removing, the position of the element is determined by the comparison of the hashcode used, so there is no offset of the element, so the efficiency is very high. Because HashSet queries and deletes and increases the efficiency of the elements are very high.
But the efficiency of hashset additions and deletions is through the cost of a lot of space in exchange: Because the larger the space, the remainder of the same situation is less. HashSet This algorithm creates a lot of useless space.
When using the HashSet interface, be aware that if there is a conflict, there will be a case of traversing the entire array, which makes the efficiency very low.
1 Packagetomtexts;2 3 4 classStudent//defining the Student class5 {6String name;//name7 intAge//Age8 PublicStudent (String pname,intPage//constructor Function9 {TenName=pname; OneAge=page; A } - } - Public classTomtexts_14//defining the main class the { - Public Static voidmain (String [] args) - { -Student [] e=NewSTUDENT[5];//declaring an array of student objects +e[0]=NewStudent ("Zhang San", 25);//invoking constructors, initializing object elements -e[1]=NewStudent ("John Doe", 30); +e[2]=NewStudent ("Harry", 35); Ae[3]=NewStudent ("Liu Liu", 28); ate[4]=NewStudent ("Zhao Qi", 32); -System.out.println ("average age" +Getaverage (e)); - GetAll (e); - } - Static intGetaverage (Student [] D)//To find the average age - { in intSum=0; - for(inti=0;i<d.length;i++) tosum=sum+D[i].age; + returnsum/d.length; - } the Static voidGetAll (Student [] D)//Output All information * { $ for(inti=0;i<d.length;i++)Panax NotoginsengSystem.out.println (d[i].name+d[i].age); - } the}
The bottom of the hashset is an array, and its query efficiency is very high