Looking at the answers to this question (link: How do I convert from int to Long in Java? ), I used the following to compare long values (newUpdate, lastUpdate) with int value (Interval)
if ((newUpdate - lastUpdate) > Long.valueOf(interval))
I am not able to compile. What is the correct way to compare two different types?
More Info:
[INFO] Trace org.apache.maven.BuildFailureException: Compilation failure [145,51] operator > cannot be applied to long,java.lang.Long
Interval is of the type int
.
If interval
is an int
, then just ...
if ((newUpdate - lastUpdate) > interval) { ...
There is NO good reason to explicitly convert interval
to a long
in this context. The conversion will be done for you anyway.
The expression Long.valueOf(Interval)
returns a java.lang.Long
rather than a long
. If you needed to explicitly turn interval
into a long
, then you should cast it:
if ((newUpdate - lastUpdate) > ((long) interval)) {
The only thing that puzzles me about your example is why you get a compilation error when comparing a long
and a Long
. The Long
should be auto-unboxed and the long
, long
version of the >
operator should be used: reference JLS - 15.20.1 which says that numeric relational operators perform unboxing if required. The only explanation can be that you are compiling with the source level at 1.4 or earlier.
Long.valueOf(Interval)
retuns wrapper object Long
hence >
operator is not applicable.
If Interval
is String type then use Long.valueOf(Interval).longValue()
in your comparison.
If Interval
is int
type then just use Interval
in your comparison. It will be auto promoted to long
--> specs .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.