2

I am trying to typecast an integer array into a long array, but I don't quite know how to go about doing this.

So far, my code looks like this:

import java.util.Random;

public class main {

public static int[] sect(){
    int[] returned = new int[4];
    Random rand = new Random();
    returned[0] = 4;
    returned[1] = rand.nextInt(8) + 1;
    returned[2] = rand.nextInt(7) + 1;
    returned[3] = rand.nextInt(6) + 1;

    return returned;
}

public static String num(){
    for (int j = 0; j < 4; j++) {
        int[] ints = sect();
        for(int i =0; i < ints.length; i++) {
            System.out.print(ints[i]);
        }
    }
    return null;
}
}

I have tried doing things like:

return ((long)num());

But that never works. Does anyone know how I would go about doing this?

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
Leo Smart
  • 49
  • 5

2 Answers2

1

You can't do that.

You simply have to create an equal sized array, and copy the int values into that array. Unfortunately System.arraycopy() can not do that for you... So you can't avoid the manual copying here.

Because an array of int isn't an array of longs. Therefore there is no such cast as from a single int into a single long.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

Are you using Java 8, if so this will work:

int[] arrayOfIntegers = {1, 2, 3, 4, 5, 6};

long[] arrayOfLongs = Arrays.stream(arrayOfIntegers).mapToLong(i -> i).toArray();
jasonlam604
  • 1,456
  • 2
  • 16
  • 25