1. = =

Data types in Java fall into two categories:

1. Basic data types, also known as primitive data types

Byte, short, char, int, long, float, double, Boolean comparison between them, the double equal sign (= =), and compare their values.

2. Reference types (classes, interfaces, arrays)

When they compare (==), they are comparing their memory location, so unless they are the same new object, their comparison result is true, otherwise the comparison result is false.

Objects are placed in the heap, and the stack holds references (addresses) to objects. It follows that ‘==’ compares values on the stack. If you want to compare the contents of objects in the heap to be the same, you override equals.

Ex. :

[url=]
[/url]


public
static
void

main(String[] args) {


int

int1 = 12;

int

int2 = 12; Integer Integer1 =

new

Integer(12); Integer Integer2 =

new

Integer(12); Integer Integer3 =

new

Integer(127); Integer a1 = 127; Integer b1 = 127; Integer a = 128; Integer b = 128; String s1 = “str”; String s2 = “str”; String str1 =

new

String(“str”); String str2 =

new

String(“str”); System.out.println(“int1==int2:” + (int1 == int2)); System.out.println(“int1==Integer1:” + (int1 == Integer1)); System.out.println(“Integer1==Integer2:” + (Integer1 == Integer2)); System.out.println(“Integer3==b1:” + (Integer3 == b1)); System.out.println(“a1==b1:” + (a1 == b1)); System.out.println(“a==b:” + (a == b)); System.out.println(“s1==s2:” + (s1 == s2)); System.out.println(“s1==str1:” + (s1 == str1)); System.out.println(“str1==str2:” + (str1 == str2));


}

[url=]
[/url]



Output result:

int1==int2:true


Int1 ==Integer1:true //Integer is automatically unpacked to int, so it is true


Integer1==Integer2:false// Different objects are stored in different memory addresses, so the value is false


Integer3==b1:false//Integer3 points to the object address of new. B1 points to address 127 in the cache. The address is different, so it is false

a1==b1:true


a==b:false

s1==s2:true


s1==str1:false


str1==str2:false


Integer b1 = 127; B1 = integer.valueof (127);

public
static

Integer valueOf(

int

i) {

assert

IntegerCache.high >= 127;

if

(i >= IntegerCache.low && i <= IntegerCache.high)

return

IntegerCache.cache[i + (-IntegerCache.low)];

return
new

Integer(i); }


If I write an Integer b1 = 127, I will cache 127. If I write an Integer i6 = 127, I will cache 127. If I write an Integer i6 = 127, I will cache 127. B1: so a1 = = true a = = b: false


2, equals

By default, equals calls the equals method of the Object class, which determines whether an Object’s memory address refers to the same address.

Here is the equals method of the Object class:

public
boolean

equals(Object obj) {

return

(

this

== obj); }


Equals by definition is equivalent to ==

2. If the equals method is overridden in a class, then it is up to the code to determine whether the equals method works.

The String class overrides equals:

[url=]

[/url]


public
boolean

equals(Object anObject) {

if

(

this

== anObject) {

return
true

; }

if

(anObject

instanceof

String) { String anotherString = (String)anObject;

int

n = count;

if

(n == anotherString.count) {

char

v1[] = value;

char

v2[] = anotherString.value;

int

i = offset;

int

j = anotherString.offset;

while

(n– ! = 0) {

if

(v1[i++] ! = v2[j++])

return
false

; }

return
true

; }}

return
false

; }

[url=]

[/url]



Equals equals equals equals equals equals equals equals


1. Return true if A==B is the same String

2. If the comparison object is a String, continue; otherwise, false is returned

3. Check whether the lengths of A and B are the same. If not, return false

4. Compare characters one by one. If unequal characters exist, false is returned


Here are five new things to note about equals:


1. Reflexivity: the return value of x.equals(X) must be true for any reference value X.


2. Symmetry: for any reference values x,y, x. quals(y) must return true if and only if y.quals (x) returns true;


3. Transitivity: if x.quals (y)=true, y.quals (z)=true, then x.quals (z)=true


4. Consistency: If there is no change in the comparison of objects, there should be no change in the comparison of objects


5. Non-null: Any non-null reference values X, x. als(null) must return false


Tips for implementing high-quality Equals methods:


1. Use the == symbol to check whether the parameter is a reference to this object. If so, return true. This is simply a performance optimization, and is worth doing if the comparison operation is likely to be expensive.


2. Use the instanceof operator to check whether the parameter is of the correct type. If not, return false. In general, the “correct type” is the class of equals.


3. Convert the parameter to the correct type. Because the instanceof test was done before the conversion, success was assured.


4. For each key domain in the class, check whether the domain in the parameter matches the corresponding domain in the object. Return true if all of these tests are successful; Otherwise return false.


5. After writing the equals method, check for “symmetry”, “transitivity”, and “consistency”.


3, hashCode

The hashCode() method returns a numeric value, which, as the name of the method indicates, is intended to generate a hash code. The main purpose of the hash code is to be used as a key input when hashing objects, so it is easy to infer that we need the hash code for each object to be as different as possible in order to ensure hash access performance. In fact, the default implementation provided by the Object class does guarantee that each Object will have a different hash code (a hash code returned by a specific algorithm based on the Object’s memory address). Java uses the principles 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. Hashing algorithm, also known as hashing algorithm, is to specify data directly to an address according to a specific algorithm. For starters, the hashCode method actually returns the physical address of the object store (it probably doesn’t).

Hash function, hash algorithm, hash function.


Is a way to create small digital “fingerprints” from any kind of data.


The hash function maps a binary value of arbitrary length to a shorter, fixed-length binary value, called a hash value.


Good hash functions have fewer hash collisions in the input field.





All hash functions have one basic property:


1: If a=b, h(a) = h(b).


2: If a! =b, then h(a) and h(b) may get the same hash value.

Object’s hashCode method: Returns an int

public
native
int

hashCode();





3.1 The purpose of hashCode


To understand this, you must first know collections in Java.


In general, there are two classes of Collections in Java: List and Set. The elements in the former set are ordered and can be repeated. The latter element is unordered, but the element cannot be repeated.

Then there is a serious problem: to ensure that elements do not repeat, what should be the basis for determining whether or not two elements repeat?

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.


That way, when you add a new element to the collection,

By calling the element’s hashCode method, you can immediately locate the physical location where it should be placed.

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. So there is a conflict resolution problem. This actually reduces the number of calls to equals to almost one or two.


4, Eqauls method and hashCode method relationship

Java rules for eqauls methods and hashCode methods are as follows:

(1) Calling hashCode() multiple times on the same object always returns the same integer value.

(2) if a. quals(b), then there must be a.ashcode () equal to B.ashcode ().


(3) if the! A. verbs (b), then A. ashCode() does not necessarily equal b. ashCode(). If a.hashcode () does not always equal b.hashcode () at this point, it will improve the performance of hashtables.

(4) A. hashcode ()== B. Hashcode (), then A. quals(b) can be true or false

(5) a.h ashCode ()! = b. hashcode (), then A. quals(b) is false.


Summary of the above conclusions:

1. If two objects are equals, the Java runtime environment assumes that their HashCode must be equal.


2. If two objects are not equals, their HashCode may be equal.


3. If two objects are equal in Hashcode, they are not necessarily equal.


4. If two objects are not equal in HashCode, they must not be equals.


Important specifications for these two methods:

Specification 1: If you override equals(Object obj), it is necessary to override hashCode () to ensure that two objects whose equals(Object obj) is true have the same hashcode() return value. To put it simply: “If two objects are the same, their Hashcodes should be equal.” Note, however: this is just a specification, so if you have to write a class that equals(Object obj) returns true and hashCode () returns two different values, it will compile and run without error. However, this violates the Java specification and bugs the program.

Specification 2: If equals(Object obj) returns false, that is, two objects are “different,” there is no requirement to call the hashcode() method on those two objects to get two different numbers. To put it simply: “If two objects are different, they may have the same Hashcode.”


5. Why always override hashCode when overriding equals


A very common error stems from not overwriting the hashCode method. In every class that overrides equals methods, hashCode methods must also be overridden. Failing to do so would violate the general convention of Object.hashCode, and would result in the class not working properly with all of the hash-based collections, such as HashMap, HashSet, and Hashtable.

1. The hashCode method must consistently return the same integer multiple times called on the same object during the execution of the application, as long as the information used by the equals method to compare the object has not been modified. During multiple executions of the same application, the integers returned by each execution can be inconsistent.

2. If two objects are equal according to equals(), then calling the hashCode method of either object must produce the same integer result.

3. If two objects are not equal according to equals(), then calling the hashCode method of either object does not necessarily produce the same integer result. But programmers should be aware that it is possible to improve hash table performance by producing radically different integer results for unequal objects.

For more technical information: Gzitcast