Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java是比较长值的正确方法_Java - Fatal编程技术网

Java是比较长值的正确方法

Java是比较长值的正确方法,java,Java,这是比较长值的正确方法吗 user.getUserId() == 3 或 我有下面的代码,其中我们比较UserID等于3 JavaMB.java if (user.getUserId() == 3) { this.setName(true); } else { this.setName(false); } Entity.java private long userId; private string name; 分贝 你提到的所有方法都是正确的。检查以下代码及其输出:

这是比较长值的正确方法吗

user.getUserId() == 3

我有下面的代码,其中我们比较UserID等于3

JavaMB.java

if (user.getUserId() == 3) {
   this.setName(true); 
   } else {
   this.setName(false);
}
Entity.java

private long userId;
private string name;
分贝


你提到的所有方法都是正确的。检查以下代码及其输出:

class Main {
    public static void main(String args[]) {
        Long l1 = 3L;
        System.out.println(l1.equals(3L));
        System.out.println(l1 == 3);

        long l2 = 3;
        System.out.println(l2 == 3L);
        System.out.println(Long.valueOf(3L).equals(l2));

        System.out.println(l1.equals(l2));
    }
}
输出:

true
true
true
true
true

两者都是正确的(只要值在
int
范围内。一旦常数超出
int
-
L
的范围,则需要
L
。另外,您可以使用
this.setName(user.getUserId()==3)替换整个if-else
尝试了两种方法都不起作用,控制台中没有错误,有些方法无法比较或等于3,用户ID是一个长值,我们正在将其与长值3进行比较,您已经向我们显示了
私有长用户ID;
,但您没有向我们显示什么
getUserId()
返回。请记住类
Integer
的实例不同(即,不与==)比较)作为
Long
的实例。您的
实体.java
不准确;它使用了
string
,这是不正确的。
Long
Long
的行为不完全相同,数据库实体的ID类型通常为空。
class Main {
    public static void main(String args[]) {
        Long l1 = 3L;
        System.out.println(l1.equals(3L));
        System.out.println(l1 == 3);

        long l2 = 3;
        System.out.println(l2 == 3L);
        System.out.println(Long.valueOf(3L).equals(l2));

        System.out.println(l1.equals(l2));
    }
}
true
true
true
true
true