Can i type cast a long type 1d array element into int?

  • A+
Category:Languages
class Test {     public static void main(String[] args) {         long[] longarr = {40, 50, 70, 90};         int sum = 0;         for (int x: (int) longarr) {             sum += x;         }         System.out.println("sum is " + sum);     } } 

how could we fix the error without making the long type array to int. is there any way to do so?

 


You have a couple of problems with your code:

  1. you cannot cast a long[] to an int[] like this --> (int) longarr, so what you need to do is leave it as for (int x: longarr) {...}
  2. Given you've changed it to for (int x: longarr) {...} a new error arises as the compiler cannot explicitly cast a long to an int therefore you can change the type of the variable to for (long x: longarr) {...}
  3. Now you can cast each long to an int before applying the summation.

This is what @Meini's approach does, but here is another approach anyway:

int summation = Arrays.stream(longarr).mapToInt(v -> (int)v).sum(); 

Note that mapToInt is required here to actually get the int value you require otherwise if we were to assign directly the summation of longs to an int variable the compiler will complain as a long can store much larger values than an int.

another version:

int summation = (int)Arrays.stream(longarr).sum(); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: