java Long datatype comparison

前端 未结 4 640
别那么骄傲
别那么骄傲 2020-12-15 03:41

Why does the code below return false for long3 == long2 comparison even though it\'s literal.

public class Strings {

    p         


        
4条回答
  •  春和景丽
    2020-12-15 03:54

    Here Long is a Wrapper class so the below line will compare the reference not the content.

    long3 == long2

    its always better to compare with ** .longValue() ** like below

    long3.longValue() == long2.longValue()

    If we use in-build equal() method that also will do the same thing with null check.

    long3.equals(long2)

    Below is the internal implementation of equals() in java

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

提交回复
热议问题