The interview will ask: == and equals the difference in Java you know

On this issue, the general middle-class interview will encounter, I still remember I had to find a job internship, they also encountered this problem, he is now still remember how to answer: == is the basic type comparison, it equals a comparison, do not know hashCode, is simply appalling to think
so

== What is that?

In the "java core technology Volume 1" == classified in the relational operator;

== commonly used in the comparison between the same basic data types, can also be compared between the same type of object;

  • == if the comparison is the basic data type, then comparing the two values ​​are equal basic data types;
  • If == is the comparison of two objects, then the comparison is a reference to two objects, that is, two objects are the same object, not a comparison of the content object;

The following example:

public class Test {
    public static void main(String[] args){
        // 对象比较
        User userOne = new User();
        User userTwo = new User();
        System.out.println("userOne==userTwo : "+(userOne==userTwo));

        // 基本数据类型比较
        int a=1;
        int b=1;
        char c='a';
        char d='a';
        System.out.println("a==b  :  "+(a==b));
        System.out.println("c==d  :  "+(c==d));
    }
}

operation result:

userOne==userTwo : false
a==b  :  true
c==d  :  true

Although userOne and objects are instances of the User userTwo, but correspond to different regions of the heap memory, so their references are also different, so as false; a and b are the basic types and therefore contrast value, the result is true; c and d is the basic type with a and b.


equals What the hell?

In the "java core technology Volume 1" to describe the Object class: Object class is the ancestor of all java classes, each class is extended from the Object class came in java; each class by default inherit the Object class, so each class has a method of class Object; so that each class has a equals method;

equals method is mainly used between two objects, detecting whether an object is equal to another object;

Below to take a look at the source code equals method of the Object class:


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

Can see the equals method of the Object class with == or, that is a reference to compare two objects are equal, not based on object property to determine whether two objects are equal; that is our own definition two object classes, if no override equals method, in fact, is used to compare ==, the method of using the results of the comparison equals == comparison with the results is the same;
Java language specification requires the following method equals characteristic:

  • Reflexivity. For any non-null reference value x, x.equals (x) must be true.
  • symmetry). To be a reference for any value of x and y null, if and only if x.equals (y) is true, y.equals (x) is true.
  • Transitive. For any non-null reference values ​​x, y and z, if x.equals (y) is true, while y.equals (z) is true, then x.equals (z) must be true.
  • consistency. To be a reference for any value of x and y null, if the information for the object equals the comparison is not modified, then, it returns true if multiple calls x.equals (y) either uniformly or consistently return false.
  • For any non-null reference value x, x.equals (null) return false.

Here let's look at a typical class;
String类
this is the jdk class, and class overrides the equals method;

Let's look at the methods in the class source code 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;
    }

As can be seen from source equals method is to compare the content;
for example:

public class Test {
    public static void main(String[] args){
        // 未重写equals方法的类
        User userOne = new User();
        User userTwo = new User();
        System.out.println("userOne.equals(userTwo) : "+(userOne.equals(userTwo)));
        //重写了equals方法的类
        String a="1111";
        String b="1111";
        System.out.println("a.equals(b) : "+(a.equals(b)));
    }
}

Here are the results:

userOne.equals(userTwo) :  false
a.equals(b)  : true

hashCode What is the role?

The method also hashCode Object class; look at the source code below hashCode method:
public native int hashCode();
This method is a local method; method returns the object's hash code (int type); related to its implementation is based on the local machine;

The following is a description of the hash of Baidu Encyclopedia:

Hash, a hash generally do translation, hash, or hash transliteration, is the input of arbitrary length (also called pre-mapping pre-image) is converted into a fixed length output by the hash algorithm, the hash value is output. This conversion is a compression map, i.e., the space hash value is typically much smaller than the input space, different inputs may hash to the same output, it is impossible to determine unique hash value from the input value. Simply means that the message of any length A to the compression function of the message digest of a fixed length.
The hash function can access more quickly and effectively process a data sequence, by a hash function, data elements will be positioned quickly

Java for eqauls and hashCode methods is such a requirement:

  • If two objects are the same, then their hashCode values ​​must be the same;
  • HashCode if two identical objects, they are not necessarily the same.
  • equals () two objects are equal, hashcode () must be equal; equals () does not equal two objects, but did not prove their hashcode () are not equal.

Where the use of hashCode?

These collections are to use the hashCode, imagine a large number of these sets of data there, if there are ten thousand, we insert or remove a piece of data to which, when inserted judge how the insertion of data already exist? How to remove the same data out? Is it one by one to compare? At this time, hashCode emerged to mention its value, and greatly reduces the processing time; this is somewhat similar to MySQL's index;

public class Test {
    public static void main(String[] args){
        //未重写hashCode的类
        User userOne = new User("aa","11");
        User userTwo = new User("aa","11");
        System.out.println(userOne.hashCode());
        System.out.println(userTwo.hashCode());
        //重写hashCode的类
        String a = new String("string");
        String b = new String("string");
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
    }
}
752848266
815033865
-891985903
-891985903

The results can be seen: userOne inconsistent and hashCode value of userTwo; hashCode consistent with a and b.

The above is the difference between == and the equals, you have to Get it?

Guess you like

Origin www.cnblogs.com/ttty/p/11752545.html