High-intensity learning and training twelfth day summary: the relationship between Java hashCode and equals

Today her things. Hastily summarized below. .

1. If the two objects are equal, it must also be the same hashcode
2. Two objects are equal, for each two objects equals method call returns to true
3. hashcode two objects have the same value, they are not necessarily equal
4. Thus, equals overridden the method, the method must be covered hashCode
5.hashCode () the default behavior is to generate a unique value for objects on the heap. If no override hashCode (), then the two objects are not equal class anyway (even if these two objects point to the same data)

equals role

Action equals () is used to determine whether two objects are equal

equals () defined in the JDK Object.java. By determining whether the same address of the two objects (i.e., whether the same object) to distinguish whether they are equal.
Source as follows:

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

hashCode () action

Role hashCode () Gets the hash code is also called a hash code; it is actually returns an int integer.
The role of this hash code is to determine the position of the object in the hash table index
function hashCode () is defined in the JDK Object.java, this means that any Java class contains hashCode ().
Although each Java class contains hashCode () function. But just when created and a "class hash table" (on "hash table" see below), the class hashCode () is only useful (role is to: determine the class of each object in the hash table position; in other cases (e.g., a single object class is created, creating an array or an object class, etc.), class hashCode () has no effect hash table above, it refers to: Java collection class is essentially the hash table. as HashMap, hashtable, HashSet that is:. hashCode () used only in the hash table, is useless in other cases in the hash table action hashCode () Gets the object is a hash code, and thus determines the object. position in the hash table.

== 与 equals

==: its role is to determine the target address is not equal to two. That is, it is determined the objects are not the same object (primitive data type is a value == comparison, the comparison reference data type == memory address).

equals (): its role is to determine whether two objects are equal. But it is generally used in two cases:

Case 1: No cover class equals () method. Through equals () comparing two objects of the class, is equivalent to the "==" to compare the two objects.
Case 2: class overrides equals () method. Generally, we cover the equals () method to compare the contents of two objects are equal; if their contents are equal, returns true (that is, the two objects are considered equal).

Guess you like

Origin www.cnblogs.com/godoforange/p/11593381.html