Is it OK to compare an int and a long in Java...
在Java中比较int和long是否可以...
long l = 800L
int i = 4
if (i < l) {
// i is less than l
}
2 个解决方案
#1
68
Yes, that's fine. The int
will be implicitly converted to a long
, which can always be done without any loss of information.
是的,没关系。 int将被隐式转换为long,这总是可以在不丢失任何信息的情况下完成。
#2
-1
You can compare long and int directly however this is not recommended.
It is always better to cast long to integer before comparing as long value can be above int limit
您可以直接比较long和int,但不建议这样做。在比较之前将long转换为整数总是更好,因为long值可以高于int limit
long l = Integer.MAX_VALUE; //2147483647
int i = Integer.MAX_VALUE; //2147483647
System.out.println(i == l); // true
l++; //2147483648
i++; //-2147483648
System.out.println(i == l); // false
System.out.println(i == (int)l); // true
#1
68
Yes, that's fine. The int
will be implicitly converted to a long
, which can always be done without any loss of information.
是的,没关系。 int将被隐式转换为long,这总是可以在不丢失任何信息的情况下完成。
#2
-1
You can compare long and int directly however this is not recommended.
It is always better to cast long to integer before comparing as long value can be above int limit
您可以直接比较long和int,但不建议这样做。在比较之前将long转换为整数总是更好,因为long值可以高于int limit
long l = Integer.MAX_VALUE; //2147483647
int i = Integer.MAX_VALUE; //2147483647
System.out.println(i == l); // true
l++; //2147483648
i++; //-2147483648
System.out.println(i == l); // false
System.out.println(i == (int)l); // true