preface

Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now

omg

Now that we’re done with lists, we’re going to talk about maps, because the underlying Set is a Map. But before WE get to Map we have to talk a little bit about equals and hashCode

🔥 Introduction to the most complete Collection of Java containers 🔥 the most complete collection of Java containers the most basic data structures (hand tear list) 🔥 the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers the most complete collection of Java containers Why are we talking about these two methods? Since Listd stores data, Map stores elements based on key-value pairs, and how elements are stored depends on equals and hashCode, so let’s examine equals and hashCode before we analyze the Map. And for a better understanding of Map in the future

The equals () method

Object’s native equals method:

   public boolean equals(Object obj) {
        return (this == obj);
    }
Copy the code

As you can see from the code, the native equals method uses “==” to compare. As anyone who has studied Java knows, “==” compares memory addresses, so the native equals method returns true only when comparing itself to itself, and is a strict way to determine whether an object is equal or not. So, if the class has its own special concept of “equal logic” (different from the concept of object equal), and the superclass does not cover the equals () method to achieve the desired behavior, then we will need to override the equals () method (popular, is in the business system, sometimes need is not a strict sense of the equal, It’s business object equality. For example, two objects are considered equal if their ids are equal.) We need to rewrite equals to define a new way to compare.

General convention to follow when overriding equals

  • Introspection: For non-null x, there is: x.exals (x) returns true
  • Symmetry: For non-null x and y, there exists: x.equials (y)== y.equials (x)
  • Transitivity: for non-null x, y, and z, it exists: when x. quals(y) returns true, y.quals (z) returns true, then x. quals(z) must be true
  • Consistency: For non-null x and y, multiple calls to x.equals(y) yield the same result
  • Non-null: For non-null x, there is x. als(null) which returns false

String overrides equals

public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- ! = 0) { if (v1[i] ! = v2[i]) return false; i++; } return true; } } return false; }Copy the code

Obviously, this is a content comparison, not an address comparison. Classes like Math, Integer, Double, etc. override equals() to compare content. Of course, the basic type is to compare values.

HashCode () method

HashCode method in String

It takes 31* the value of the previous character + the size of the current character, and iterates to get the hash value of String

In Object, hashCode is a Native method. HashCode is usually used to calculate the hash value of an object. It is overridden when the equals class overrides it to ensure that the hashCode results of two equals objects are the same. Such as HashMap, HashSet, etc., these collections need to use the hash value of the object to participate in the calculation and positioning. The purpose of hashCode is to hash elements, and whether the elements hash evenly depends on the implementation of hashCode, which is the hash function.

The role of hashCode

To understand what hashCode does, we need to go back to what we call containers. In Java, collections have two classes: a List and a Set. The elements in the former set are ordered and can be repeated. The latter element is unordered, but the element cannot be repeated. This raises the question: what is the basis for determining whether two elements are duplicated in order to ensure that elements are not duplicated?

So that’s object.equals. However, if you check each additional element, then when there are many elements, the number of comparisons between the elements added to the collection is very high. That is, if the collection already has 1000 elements, it will call equals 1000 times when the 1001st element is added to the collection. This is obviously a huge loss of efficiency.

So, Java adopted the principle of hash tables. A Hash is actually a person’s name, named after him because he came up with the idea of a Hash algorithm. A hash algorithm, also known as a hash algorithm, assigns data directly to an address based on a specific algorithm. For starters, the hashCode method actually returns the physical address of the object store (which may not be the actual address).

That way, when you add a new element to the collection, you call the element’s hashCode method, and you can immediately locate it in its physical location. If there is no element in this location, it can be stored directly in this location without any comparison; If there is already an element at that location, its equals method is called to compare it with the new element. If they are the same, they are not saved. If they are different, the other address is hashed. So there is a conflict resolution problem. This actually reduces the number of calls to equals to almost one or two.

conclusion

The eqauls method and the hashCode method are specified in this way

  • If two objects are the same, their hashCode values must be the same;
  • If two objects have the same hashCode, they are not necessarily the same (by same object I mean eqauls method comparison).
  • Hashcode () must be equal to equals(); Two objects whose equals() is not equal does not prove that their hashcode() is not equal.
  • Why override equals? In Java’s collection framework, equals is used to determine whether two objects are equal

Release notes

  • The source code here is JDK8 version, different versions may vary, but the basic principle is the same.

At the end

So now that we’re done with hashCode and equals, we can figure out how to make sure that we don’t duplicate the data we’re storing. Let’s start with HashMap.

I have a goal to write two or three articles a week. I hope I can keep it up for a year. I hope you can give me more suggestions so that I can learn more and make progress together.

Daily for praise

All right, everybody, that’s all for this article. All the people here are talented.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!