开发者

How to Compare a long value is equal to Long value

long a = 1111;
Long b = 1113;
    
if (a == b) {
    System.out.println("Equals");
} else {
    System.out.println开发者_如何学JAVA("not equals");
}

The above code prints "equals", which is wrong.

How do I check whether a long value equals a Long value?


First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".


It works as expected:

public static void main(String[] args) {
    long a = 1111;
    Long b = 1113l;

    if (a == b) {
        System.out.println("Equals");
    } else {
        System.out.println("not equals");
    }
}

prints not equals.

Use compareTo() to compare Long, == wil not work in all case as far as the value is cached.


long a = 1111;
Long b = new Long(1113);

System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");


Long is an object, while long is a primitive type. In order to compare them, you could get the primitive type out of the Long type:

public static void main(String[] args) {
    long a = 1111;
    Long b = 1113;
    if ((b != null) && (a == b.longValue())) {
        System.out.println("Equals");
    } else {
        System.out.println("not equals");
    }
}


Since Java 7 you can use java.util.Objects.equals(Object a, Object b):

These utilities include null-safe or null-tolerant methods

Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));


You can use the equals method to compare Object values.

Mismatch example:

Long first = 12345L, second = 123L;
System.out.println(first.equals(second));

This returns false.

Match example:

Long first = 12345L, second = 12345L;
System.out.println(first.equals(second));

This returns true.


First option:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if (a == b.longValue()) {
            System.out.println("Equals");
        } else {
            System.out.println("not equals");
        }
    }

Second option:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if (a == b) {
            System.out.println("Equals");
        } else {
            System.out.println("not equals");
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜