简体   繁体   中英

Return types in Java - long to int casting - IntelliJ complains?

So I have this method:

在此处输入图片说明

So why is IntelliJ warning me that return x is not allowed there, but it is ok just above? The id of class ProjectElement is also of type long.

Please do not answer the question without actually reading it. :)

I assume by "it is ok just above" you refer to is:

return (p1.getId().compareTo(p2.getId());

That's not returning the ID (which is a Long ) - it's returning the result of the compareTo method, which is an int . (See the Long.compareTo(Long) documentation .)

There's no implicit conversion from long to int , which is why your statement of return x; is invalid.

It seems to me that all you need to do is change the declaration of x to be int instead of long - you're only populating it from the result of a compareTo call, after all:

// Removed extraneous brackets as well...
int x = p1.getCustomerUnit().getId().compareTo(p2.getCustomerUnit().getId());
if (x == 0) {
    return p1.getId().compareTo(p2.getId());
}
return x;

It's important to distinguish between the type of the ID, and the type of the result of a comparison between IDs.

Error is because, compare() method declares to return int , you are returning long .

ProjectElement 's Id variable is type of Long, and Long 's compare() method return int .

(p1.getId().compareTo(p2.getId()) returning int, since Id is type of Long , and Long's compare() method return int

The reason for complaining is that returning a long for an int would cause truncation, you're throwing away half the bits!

If you really must do this, cast it: return (int)x; and be prepared for the consequences :-)

Cheers,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM