1

I've just begun using java and I can't convert a long array type to int array. Can you give a piece of advice what should I do? Thank you!

public class Main {
    public static void main(String[] args) {
        long[] numbers;
        numbers = sorting(new long[]{5, 21, 19, 55, 94, 73, 69, 100,});



    }

    public static long[] sorting(long [] numbers) {

        for (long num : numbers) {
            long j = 0;
            for (int i = 0; i < numbers.length - 1; i++) {
                if (numbers[i] > numbers[i + 1]) {
                    j = numbers[i];
                    numbers[i] = numbers[i + 1];
                    numbers[i + 1] = j;


                }
            }
            System.out.println(num + ",");
        }
        return (numbers); 
Inna S
  • 31
  • 1
  • 4

3 Answers3

2

To convert an long[] to int[], you need to iterate over your long[] array, cast each individual number to int and put it to the int[] array.

// Your result
long[] numbers = sorting(new long[] {5, 21, 19, 55, 94, 73, 69, 100});

// Define a new int array with the same length of your result array
int[] intNumbers = new int[numbers.length];

// Loop through all the result numbers
for(int i = 0; i < numbers.length; i++)
{
    // Cast to int and put it to the int array
    intNumbers[i] = (int) numbers[i];
}

Or you can also use Java Streams (>= 1.8) for a shorter version:

int[] intArray = Arrays.stream(numbers).mapToInt(i -> (int) i).toArray();

bbrinck
  • 953
  • 1
  • 9
  • 33
2

There is a similar question in convert-an-int-array-to-long-array-using-java-8

You can try this:

    long[] longArray = {1, 2, 3};
    int[] intArray = Arrays.stream(longArray).mapToInt(i -> (int) i).toArray();
bbrinck
  • 953
  • 1
  • 9
  • 33
Arman Fatahi
  • 2,635
  • 3
  • 24
  • 37
0

Something else to mention here. If you just cast long to int you risk an integer overflow. So to be safe I would recommend Math#toIntExact function which ensures the conversion is safe. Here is an example:

long[] longs = new long[] {1,2,3,4,5};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray();

If longs contains a value that can't be converted to an int then an ArithmeticException will be thrown e.g.

long[] longs = new long[] {1,2,3,4,5, Long.MAX_VALUE};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray(); // Throws here

will throw Exception in thread "main" java.lang.ArithmeticException: integer overflow this ensures your code works correctly.

James Mudd
  • 1,816
  • 1
  • 20
  • 25