[Java learning notes] objects of custom classes added to hashset

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

This topic is derived from a problematic code. The original code is as follows:

Import java. util .*;
Class treesettest
{
Public static void main (string [] ARGs)
{
Hashset HS = new hashset ();
Student ST1 = new student (1, "zhao1 ");
Student st2 = new student (1, "zhao1 ");
HS. Add (ST1 );
HS. Add (st2 );
System. Out. println (HS );
}
}
Class student
{
Public student (INT num, string name)
{
This. num = num;
This. Name = Name;
}
Public int hashcode ()
{
Return new INTEGER (Num). hashcode ();
}
Public Boolean equals (student st)
{
If (name = ST. Name) return true;
Else return false;
}
Public String tostring ()
{
Return "student" + num + "name:" + name;
}
Int num;
String name;
}

Why can ST1 and st2 objects have the same content but can still be inserted into a set? Isn't set a repeated object?

There are two main problems with this program:

JavaOverload overload:
As long as it is a class and two functions in its parent classWith the same name but different parameter lists(This includes one or more of the three parameter types, number of parameters, and Parameter order ).The overload can appear in a single class or two classes with inheritance relationships.Is an important way to realize the polymorphism of classes.

JavaOverride:
Overwriting only appears when the class is inherited. Overwriting requires that the names and parameter lists of both functions are identical.

The equals method is used to determine whether a repeated element is used in the hashset. However, note that the custom class actually inherits the object class, And the equals method in the object class is defined as follows:

Public Boolean equals (Object O)

In this case, The equals method defined in this program is to overload the equals method in the object, rather than overwrite it. When the hashset judges duplicate elements, it actually calls the object. the equals method is true.

Therefore, the first thing that needs to be modified for this program is the equals method: We need to overwrite it, not overload it. To prevent this problem, we can add annotation to let eclipse determine it by itself.


Public Boolean equals (Object st)
{
Student tempstudent = (student) ST;
If (name = tempstudent. Name) return true;
Else return false;
}

In addition, the hashcode method of the program segment in the Custom class is inconsistent with equals. The former uses num as the basis for the hashcode method, and the latter uses name as the basis for determining whether the hashcode method is the same.

1) when the hashset/hashmap/hashtable class is used to store data, it is determined whether the hashcode value of the stored object is the same. In hashcode, only two objects have the same hashcode () the equals method is called to compare, because the hashset uses the remainder of a number n to partition the hash code, that is, even if the hash code is different, they may also be divided into the same region. When adding data, calculate the hashcode (String object hash code calculated according to the following formula: s [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1] Note: The Int algorithm is used. Here, s [I] is the I character of the string, n is the length of the string, and ^ represents the power. (The Hash Value of the Null String is 0). It is found that the equals method is used to compare whether the objects in the same region are the same one by one. Otherwise, they are inserted directly.

|

| Region 1 | Region 2 | ......

|

This area uses the linked list method during implementation.

When the add method of hashset is called to store the object OBJ, hashset first calls the hascode method of OBJ to obtain the hash code of the object, hashset uses an algorithm to convert its hash code into an array subscript, which marks the position of obj. If there are no elements in the linked list at this position, add the OBJ object to the linked list. If an element already exists in the linked list at this position, traverse the linked list and call the equals method of OBJ to determine whether the object is duplicated with one of the elements. If no duplicate element exists, the obj is added to the linked list. If there are repeated elements, the OBJ object is not stored in the hashset.

That is to say,According to the definition of the hash table, to ensure that the same object is put in the same hash area, the condition must be met: if equals () exists, true => hashcode () is returned and true is returned.Because the value of hashcode is first determined. In other words, if the value of equals is true, it is a sufficient and unnecessary condition for the value of hashcode to true.In this way, there will be no two identical objects, just because they are not in the same hash region and are mistakenly added to the hash set.

2) because the slow query speed is the disadvantage of the linked list, when we define our own hashcode () and equals,To take care of the performance of the hash tableThe hashcode must also be set to false when equals returns false"

Based on the above 1) and 2), if the hashcode method is inconsistent with equals, there is no relationship between hashcode () and equals () results. That is to say, when equals returns true, hashcode () it may also be false. This does not conform to the definition of elements that cannot be the same as that in the hash table definition, or the performance optimization needs of the hash table.

The conclusion is that it is recommended that the hashcode and equals methods should be based on one principle, that is, the two methods are compatible.

Note: After an object is stored in a hashset, you cannot modify the fields involved in calculating the hash value. Otherwise, the modified hash value of the object is different from the hash value originally stored in the hashset object. In this case, even if the contains method uses the current reference of this object as the parameter to retrieve the hashset set, the result of the object not found is returned, which leads to the failure to separately Delete the current object from the hashset set, this results in Memory leakage.

The instance code is as follows:

Package testhashcode;
/**
* @ Author gnuhpc
* Email: warmbupt@gmail.com
* Blog: http://blog.csdn.net/gnuhpc
* @ Date 2010-1-13
*/
Import java. util .*;
Class treesettest
{
Public static void main (string [] ARGs)
{
Hashset <student> HS = new hashset <student> ();
Student ST1 = new student (1, "Zhao ");
Student st2 = new student (2, "Qian ");
Student st3 = new student (3, "Sun ");
HS. Add (ST1 );
HS. Add (st2 );
HS. Add (st3 );
System. Out. println (HS );
St1.num = 4;// Try to comment out this line and check the result.
HS. Remove (ST1 );
System. Out. println (HS );
}
}
Class student
{
Public student (INT num, string name)
{
This. num = num;
This. Name = Name;
}
Public int hashcode ()
{
Return new INTEGER (Num). hashcode ();
}
@ Override
Public Boolean equals (Object st)
{
Student tempstudent = (student) ST;
If (num = tempstudent. Num) return true;
Else return false;
}
Public String tostring ()
{
Return "student" + num + "name:" + name;
}
Int num;
String name;
}

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.