The need for Java to judge whether two objects are equal equals and hashcode ()

Source: Internet
Author: User

Only use to Hashtable, HashMap, HashSet, Linkedhashmap and so on to pay attention to hashcode, other places hashcode useless. (So understanding is not necessarily right)

Whether the two objects are equal or not requires hashcode () equality, and whether the statement below

In the Java collection, the rule that determines whether two objects are equal is:
1) to determine whether the hashcode of two objects is equal
If not equal, the two objects are not equal, complete
If equal, transfer to 2)
(This is only to improve the storage efficiency of the requirements, in fact, can not, in theory, but if not, the actual use of efficiency will be greatly reduced, so we here to do it as required.) We will focus on this issue later. )
2), to determine whether two objects are equal with the equals operation
If not equal, two objects are considered unequal
If equal, two objects are considered equal (equals () is the key to determining whether two objects are equal)

I personally feel that the above statement is hashset rule that determines whether elements are duplicated (because HashSet does not allow elements to repeat)

Instead of Hashtable, HashMap, HashSet, and Linkedhashmap calling equals in your code, you can tell if they're equal.

Take a look at the example below

Class Name
{
Private String A;
Private String last;

Public Name (String A, last, string)
{
This.first = A;
This.last = Last;
}

public boolean equals (Object O)
{
if (this = O)
{
return true;
}

if (o.getclass () = = Name.class)
{
Name n = (name) o;
Return N.first.equals (a)
&& n.last.equals (last);
}
return false;
}
}

public class Hashsettest
{
public static void Main (string[] args)
{
set<name> s = new hashset<name> ();
S.add (New Name ("abc", "123"));
System.out.println (
S.contains (New Name ("abc", "123"));
}
}
Class Name
{
Private String A;
Private String last;

Public Name (String A, last, string)
{
This.first = A;
This.last = Last;
}

    public boolean equals (Object o)
    {
         if (this = = O)
        {
             return true;
       }
       
 if (o.getclass () = Name.class)
         {
            name n = (name) o;
            return N.first.equals (a)
                 && N.last.equals ( last);
       }
        return false;
   }
}

public class Hashsettest
{
public static void Main (string[] args)
{
set<name> s = new hashset<name> ();
S.add (New Name ("abc", "123"));
System.out.println (
S.contains (New Name ("abc", "123"));
}
}


After adding a new name ("abc", "123") object to HashSet in the above program, the program immediately determines whether the hashset contains a new name ("abc", "123") object. Coarse looks, it is easy to assume that the program will output true.

Actually running the program above will see the program output false, because hashset the criteria for determining that two objects are equal, in addition to the requirement to return true by comparing the Equals () method, also requires that the hashcode () return value of two objects be equal. The above program does not override the Hashcode () method of the name class, and the Hashcode () return values for the two name objects are not the same, so hashset treats them as 2 objects, so the program returns FALSE.

Thus, it is important to override the Equals (Object obj) method and the Hashcode () method of a class when we try to use it as a HashMap key, or when we try to put an object of that class into HashSet. Also, the return values of the two methods must be consistent: when the two hashcode () return values of the class are the same, they should return true by comparing them through the Equals () method. In general, all key attributes that participate in the calculation of the hashcode () return value should be used as the criteria for equals () comparisons.
The following procedure correctly rewrites the hashcode () and Equals () methods of the Name class, as follows:

Java code
Class Name
{
Private String A;
Private String last;
Public Name (String A, last, string)
{
This.first = A;
This.last = Last;
}
Determine whether two Name is equal according to first
public boolean equals (Object O)
{
if (this = O)
{
return true;
}
if (o.getclass () = = Name.class)
{
Name n = (name) o;
Return N.first.equals (a);
}
return false;
}

Returns a value based on the hashcode () of the Name object
public int hashcode ()
{
return First.hashcode ();
}

Public String toString ()
{
Return "name[first=" + the "+", last= "+ Last +"];
}
}

public class HashSetTest2
{
public static void Main (string[] args)
{
hashset<name> set = new hashset<name> ();
Set.add (New Name ("abc", "123"));
Set.add (New Name ("abc", "456"));
SYSTEM.OUT.PRINTLN (set);
}
}
Class Name
{
Private String A;
Private String last;
Public Name (String A, last, string)
{
This.first = A;
This.last = Last;
}
Determine whether two Name is equal according to first
public boolean equals (Object O)
{
if (this = O)
{
return true;
}
if (o.getclass () = = Name.class)
{
Name n = (name) o;
Return N.first.equals (a);
}
return false;
}

Returns a value based on the hashcode () of the Name object
public int hashcode ()
{
return First.hashcode ();
}

Public String toString ()
{
Return "name[first=" + the "+", last= "+ Last +"];
}
}

public class HashSetTest2
{
public static void Main (string[] args)
{
hashset<name> set = new hashset<name> ();
Set.add (New Name ("abc", "123"));
Set.add (New Name ("abc", "456"));
SYSTEM.OUT.PRINTLN (set);
}
}


The above program provides a name class that overrides Equals () and toString () two methods, both of which are based on the first instance variable of the name class, and when the first instance variable of the two name object is equal, the two N The Hashcode () return value of the Ame object is also the same, and returns True by Equals () comparison.

The program Main method first adds the first name object to the HashSet, and the name object has an initial instance variable value of "ABC", and then the program attempts to add a name object named "ABC" to the HashSet, and it is obvious that the new Na The Me object is added to the HashSet because the name object you are trying to add is the "ABC", HashSet will judge that the new name object here is the same as the original name object and therefore cannot be added, and the program prints the set collection at the ① code to see To the collection contains only one name object, which is the first, last is "123" name object.

HashSet the bottom of the use of HashMap to save all elements, save with HashMap key, the Righteousness HashMap key to determine whether the key is equal from the hashcode and equals is equal to judge

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.