How to initialize an array in a loop in java?

I take the size of the array in a variable in a loop. Every time I have to assign an array size equal to this variable, and then take integers equal to this size. For instance:

for(i = 0; i < N; i++)
{
    variable = sc.nextInt();
    int []array = new int[variable];
    for(j = 0; j < variable; j++)
    {
        array[j] = sc.nextInt();
    }
}

Please provide me with the most efficient method since I am new to java :)

+4
source share
3 answers

Maybe you need something like this:

List<int[]> list = new ArrayList<>();//create a list or arrays
for (int i = 0; i < n; i++) {

    int variable = sc.nextInt();
    int[] array = new int[variable];
    for (int j = 0; j < variable; j++) {
        array[j] = sc.nextInt();
    }

    list.add(array);//add your array to your list
}
+1
source

You can create a list of arrays and initialize them on the outer loop and add values ​​to the arrays using the iand positions j.

// initialize list with n, though you can also use 2D array as well
List<int[]> array = new ArrayList<>(n);

for (int i = 0; i < n; i++) { 
    variable = sc.nextInt();

    // create an array and add it to list
    array.add(new int[variable]);

    for (int j = 0; j < variable; j++) {
        // fetch the array and add values using index j
        array.get(i)[j] = sc.nextInt();
    }
}
0
source
for(i=0;i<N;i++)
{
    variable = sc.nextInt();
    ArrayList array = new ArrayList(variable)
    for(j=0;j<variable;j++)
    {
        int input = sc.nextInt()
        array.add(input);
    }
}

ArrayList, .

-1

Source: https://habr.com/ru/post/1678005/


All Articles