To compare in java, we need to choose the appropriate comparison method according to the type of comparison:
-
Object: Use equals.
-
Enumeration: use equals or ==.
-
Objects that may be null: Use == and equals.
-
Array: Use Arrays.equals.
-
Primitive data types (except float and double): Use ==.
-
Float type: Use Float.foatToIntBits to convert to int type, and then use ==.
-
Double type: Use Double.doubleToLongBit to convert to long type, and then use ==.
As for 6) and 7) why conversion is needed, we can refer to the equals() method of their corresponding package class. The following is of the Float class:
public boolean equals(Object obj) {
return (obj instanceof Float)
&& (floatToIntBits(((Float)obj).value) == floatToIntBits(value));
}
The reason, there are two points mentioned:
However, there are two exceptions:
If f1 and f2 both represent
Float.NaN, then the equals method returns
true, even though Float.NaN==Float.NaN
has the value false.
If <code>f1 represents +0.0f while
f2 represents -0.0f, or vice
versa, the equal test has the value
false, even though 0.0f==-0.0f
has the value true.
ref: https://www.cnblogs.com/lori/p/8308671.html
Original: https://www.cnblogs.com/frankcui/p/10810672.html