简体   繁体   中英

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

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 long s 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();

Try

public static void main(String[] args) {
    long[] longarr = {40, 50, 70, 90};
    int sum = 0;

    for (long x : longarr) {
        sum += (int)  x;
    }
    System.out.println("sum is " + sum);
}

Actually you don't have to explicitly cast x to int -> sum += x; , i leave it there to make it more clearly

Your question was must be :

how to fix error : incompatible types: long cannot be converted int

Change in the loop to :

 public class NewClass {  
      public static void main(String[] args) {

            long[] longarr = {40, 50, 70, 90};
            int sum = 0 ; 

            for (long  x: longarr  ) { // don't need cast 
                sum += x;
            }
            System.out.println("sum is " + sum);
        }
         }

run:

 sum is 250

Correct :

for (long x : longarr) {

}

No need to do an explicit type cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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