简体   繁体   English

Java中的返回类型-长到int强制转换-IntelliJ抱怨吗?

[英]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? 那么,为什么IntelliJ警告我那里不允许返回x,但是在上面可以吗? The id of class ProjectElement is also of type long. 类ProjectElement的id也是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 . 那不是返回ID(它是Long ),而是返回compareTo方法的结果,它是一个int (See the Long.compareTo(Long) documentation .) (请参阅Long.compareTo(Long)文档 。)

There's no implicit conversion from long to int , which is why your statement of return x; longint没有隐式转换,这就是为什么您的return x;语句的原因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: 在我看来, 所有你需要做的是改变的声明xint而不是long -你只能从结果填充它compareTo通话,毕竟:

// 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. 区分ID的类型和ID之间的比较结果的类型非常重要。

Error is because, compare() method declares to return int , you are returning long . 错误是因为, compare()方法声明返回int ,您正在返回long

ProjectElement 's Id variable is type of Long, and Long 's compare() method return int . ProjectElement的Id变量是Long的类型,而Longcompare()方法返回int

(p1.getId().compareTo(p2.getId()) returning int, since Id is type of Long , and Long's compare() method return int (p1.getId().compareTo(p2.getId())返回int,因为Id的类型为Long ,和长期的compare()方法返回INT

The reason for complaining is that returning a long for an int would cause truncation, you're throwing away half the bits! 之所以抱怨是返回longint会导致截断,你把自己一半的位!

If you really must do this, cast it: return (int)x; 如果确实必须执行此操作,则将其强制转换为: return (int)x; and be prepared for the consequences :-) 并为后果做好准备:-)

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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