In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the role of equals and hashCode in java". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the role of equals and hashCode in java".
Equals
I won't say any more about when to override the equals method. I'm sure readers familiar with Java will know that we'll focus on how to write the equls method of the specification. Because a nonstandard equals method will cause the collection to fail to behave as expected.
Overriding the equals method requires that the equals meets the following characteristics:
Reflexivity: for any non-null reference value x, x.equals (x) must return true symmetry: for any non-null reference values x and y, if and only if y.equals (x) returns true, x.equals (y) must return true transitivity: for any non-null reference values x, y, z, if x.equals (y) returns true and y.equals (z) returns true Then x.equals (z) must also return true consistency: for any non-null reference values x, y, as long as the field information involved in equals has not been modified, calling x.equals (y) multiple times to return the same result non-null: for any non-null reference value x _ mag _ X.equals (null) must return false reflexivity.
This requirement states that the object must be equal to itself, and if you violate this rule, the contains method that you will send the collection cannot tell you the correct result.
Symmetrical property
Symmetry requires two objects to be consistent as to whether they are equal. The following code violates symmetry.
Public class IgnoreCaseString {
Private final String s
Public IgnoreCaseString (String s) {this.s = s;}
@ Override public boolean equals (Object obj) {if (obj instanceof IgnoreCaseString) {return s.equalsIgnoreCase (IgnoreCaseString) obj) .s);} if (obj instanceof String) {return s.equalsIgnoreCase ((String) obj);} return false;}
Public static void main (String [] args) {IgnoreCaseString ignoreCaseString = new IgnoreCaseString ("Phone"); String string = "phone"; System.out.println (ignoreCaseString.equals (string)); System.out.println (string.equals (ignoreCaseString)); System.out.println ("-"); List list = new ArrayList () List.add (string); System.out.println (list.contains (ignoreCaseString));}} transitivity
This usually happens in objects that have a parent-child relationship, and the added information of the subclass affects the result of the equals comparison. There are usually two ways to solve this problem, one is through getClass () (specifically, you can read the book Effective Java), and the other is to use composition instead of inheritance as far as possible when we expand the function of the class, which can also be solved by comparing the domains in the composite components.
Consistency
Consistency requires that if two objects are equal, they must remain equal unless one of them is modified.
Nonemptiness
Non-null requires that all objects are not equal to null
How to write equals if the operation is expensive, you can first use the = = operator to check whether it is the same object reference and use the instanceOf operator to check whether the parameter is of the correct type (the correct type usually refers to the class in which the equals method is located, but sometimes it is also an interface implemented by this class, such as Set, List, etc.) to convert the parameter to the correct type for each key field in the class Check that the fields in the parameters match the corresponding fields in the object. For fields of primitive types that are neither float nor double, you can use the = = operator to compare, recursively call the equals method for reference types, use the Float.compare method for float, use the Double.compare method for double, and use the Arrays.equals method for array fields. The most important step is to do a unit test when you finish writing the equals method to verify that the equals method meets the above characteristics. HashCode
In every class that overrides the equals method, the hashCode method must be overridden. Failure to do so will prevent the class from working properly with all hash-based collections. The hashCode method needs to follow the following rules:
During program execution, as long as the information used in the object's equals method comparison operation is not modified, the same integer must be returned if the hashCode method is called multiple times for the same object. However, in multiple executions of an application, the integers that can be returned for each execution can be inconsistent. If the comparison results of two objects are equal according to the equals method, then calling the hashCode method of either object must produce the same result. If the two objects do not want to wait according to the equals method, then calling the hashCode method of the two objects can produce the same or different integer results. But try to make sure that the program can produce different integers, because this can improve the performance of the hash table. How to write a non-zero constant value in hashCode, for example, 17 is saved in an int type variable of result. For each field (f) involved in the equals method in the object, the hash code is merged into result according to result = 31 * result + c (the hash code calculated in the second step) and returns the hashCode method that validates itself.
The reason for using a non-zero initial value is that fields with an initial value of 0 can affect the hash value. If 0 is used, the hash value will no longer be affected by these fields, thus increasing the possibility of Hash conflicts and reducing the performance of the hash table.
31 is an odd prime, which will be removed if two larger numbers are multiplied in Java. 31 is not a relatively large number. The reason for choosing 31 is that shift and subtraction can be used instead of multiplication. 31 * I = (I > 32) if it is float type, calculate Float.floatToIntBits (f) if it is double type, calculate Double.doubleToLongBits (f), and then calculate the hash value if it is a reference type. Recursive call hashCode if it is an array, call the Arryas.hashCode method
If a class is immutable and the cost of calculating the hash code is high, consider caching the hash code inside the object instead of recalculating it every time you request it (this is also true in Kafka).
Thank you for reading, the above is the content of "what is the role of equals and hashCode in java". After the study of this article, I believe you have a deeper understanding of what the role of equals and hashCode in java is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.