Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise an array in a loop in java?

I am taking the size of an array in a variable in a loop. Each time I have to assign the size of the array equal to that variable and then take integers equal to that size. For example:

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 the most efficient method as I am new to java :)

like image 990
Alfran Avatar asked Nov 07 '22 21:11

Alfran


1 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
}
like image 54
YCF_L Avatar answered Nov 15 '22 07:11

YCF_L