[Java] Note the case where equals is false but == is ture.

When I was investigating the equivalence relation, Java equals came out, so make a note

-== is false --true with equals

I think you know well when it becomes. This is the time when they are different instances and have the same value.

vice versa

-== is true --false with equals

I don't think the case of becoming is very familiar.

This time we will verify the matter.

environment: Java1.8 Eclipse Neon.1

Source of problem

python


	@org.junit.Test
	public void test() {
		boolean b1 = 1 == 1.0;
		
		Integer i2 = 1;
		boolean b2 = i2==1.0;        //true
		boolean b3 = i2.equals(1.0); //false

		System.out.println(b2);
		System.out.println(b3);
		
		
	}

Commentary

Double # valueOf is called to auto boxing a double type 1.0 to a double type.

auto-boxing


    public static Double valueOf(double d) {
        return new Double(d);
    }

It will be false because it will be a comparison using equals between 1.0 converted to Double type and 1 of Integer type.

Integer.equals()


    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

Be careful with auto boxing.

Java Puzzle has a similar problem with auto boxing.

https://www.youtube.com/watch?v=V1vQf4qyMXg&t=11m19s

auto boxing can give you what we call the surprise left jab

by Joshua Bloch

Recommended Posts

[Java] Note the case where equals is false but == is ture.
Where is the Java LocalDateTime.now () timezone?
The comparison of enums is ==, and equals is good [Java]
Java is the 5th day
[Note] Java: Is it necessary to override equals for equality judgment?
My thoughts on the equals method (Java)
[rails] The case where the server stopped working
What is the best file reading (Java)
What is the main method in Java?
The Java EE Security API is here!
[Java] Where is the implementation class of annotation that exists in Bean Validation?
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?