Java Auto Boxing and conditional operator

无人久伴 提交于 2019-12-13 16:30:30

问题


In sonar i see a major violation warning for code

  public Long getValue(FieldType fieldType) {
    Long value = paramLevelMap.get(fieldType); // ok returns Long not long
    return value == null ? UNSPECIFIED_PARAMETER_KEY : value; // complaints here
  } 

Where 'UNSPECIFIED_PARAMETER_KEY' is pvt static long , and 'value' is also long.

Boxed value is unboxed and then immediately reboxed

Its complaining on the 2nd line. I didn't quite understand it , when & how is primitive long being converted to corresponding class object ? and back ?


回答1:


The return type of a ternary (or more correctly, conditional) expression where the second and third operands consist of one primitive and one corresponding boxed version, is that of the primitive.
(For a complete analysis of the type of the conditional operator, look at the Java Specifications 15.25.)

Since the second operand here, UNSPECIFIED_PARAMETER_KEY, is a long, and the third, value is a Long, Java has to unbox value to a long to evaluate the expression.

After this, a Long is to be returned, so value is immediately reboxed.

You can fix this by changing your constant UNSPECIFIED_PARAMETER_KEY into a Long.



来源:https://stackoverflow.com/questions/16856998/java-auto-boxing-and-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!