-2

I am unable to figure out where the boxed value is unboxed and again reboxed in below sample piece of code. Can some one pls help me in fixing this sonar bug.

List<Float> floatList = new ArrayList<>();
Float hundred = 100F;
Float zero = 0F;
String []stringFloatValues= new String[]{1.2,3.44,5.66};

for(String stringFloat: stringFloatValues){
    Float value = NumberUtils.isParsable(stringFloat)
           ? Float.valueOf(stringFloat) / hundred
           : zero;  // sonar showing issue in this statement
    floatList.add(value);
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Bhargav V
  • 9
  • 3
  • "sonar showing issue in this statement" Every expression in that statement of type `Float` should be a `float`: `Float.valueOf(stringFloat) => Float.parseFloat(...)`, `Float hundred => float hundred`, `Float zero => float zero`. But also, there's little point in defining variables with easily-understood values: just use `100F` instead of `hundred` etc. – Andy Turner Nov 09 '20 at 16:10
  • Actually, I implemented float instead of Float earlier it self. but still issue is not resolving. So, I thought I should use Float only because If I use float then again autoboxing will happen to store the result into value variable. so I converted that statement to Float values. – Bhargav V Nov 09 '20 at 16:27

1 Answers1

0
List<Float> floatList = new ArrayList<>();
float hundred = 100F;
float zero = 0F;
String[] stringFloatValues = new String[]{"1.2", "3.44", "5.66"};

for (String stringFloat: stringFloatValues) {
    float value = NumberUtils.isParsable(stringFloat)
           ? Float.parseFloat(stringFloat) / hundred
           : zero;  // sonar showing issue in this statement
    floatList.add(value);
}

As you calculate, do a division (/), keep everything as primitive type float. Float.valueOf would give a boxed Float, which would need to be unboxed to float, as also hundred. As above - with parseFloatgiving a float -, the resulting float value will be boxed on add.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138