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); 
1
  • 1
    Do you want to convert the long array to int array? Commented Nov 29, 2019 at 6:23

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yes, but this does not work, because i needs to be converted to int first.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.