What type is compared with equals() and what type is compared with ==

To compare in java, we need to choose the appropriate comparison method according to the type of comparison:

  1. Object: Use equals.

  2. Enumeration: use equals or ==.

  3. Objects that may be null: Use == and equals.

  4. Array: Use Arrays.equals.

  5. Primitive data types (except float and double): Use ==.

  6. Float type: Use Float.foatToIntBits to convert to int type, and then use ==.

  7. 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

 

Guess you like

Origin blog.csdn.net/cherry_vicent/article/details/111473544