Search code examples
javaarraysprimitiveshort

Calculation the average of short type array in JAVA


Let's say I have a short[] thisArray in JAVA, and I need to calculate the average based on the amount of elements in this array. But apparently, .length will return a int number to represent the length of thisArray.

I cannot convert it into int Array or int, since it is not allowed to convert int back to short. I do need to have a short result and store back into another short[][].

How to avoid this classic error: error: incompatible types: possible lossy conversion from int to short short result = sum / thisArray.length;

public static short getSum(short[] sumArray) {
  short sum = 0;
  for(short i : sumArray) {
    sum += i;
  }
  return sum;
}

sum = getSum(thisArray);

short result = sum / thisArray.length;

Solution

  • If you know for sure the average can fit into a short variable, you just have to cast the result:

    short result = (short)(sum / thisArray.length);
    

    I'd also change sum to int, to reduce the risk of overflow (which may occur if the sum is larger than 32767).

    To summarize:

    public static int getSum(short[] sumArray) {
      int sum = 0;
      for(short i : sumArray) {
        sum += i;
      }
      return sum;
    }
    
    ...
    
    int sum = getSum(thisArray);
    
    short result = (short) (sum / thisArray.length);