Alfran
Alfran

Reputation: 1441

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 :)

Upvotes: 5

Views: 8885

Answers (3)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You can create a list of arrays and initialize them on outer loop and add values to arrays using position i and 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();
    }
}

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

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
}

Upvotes: 1

Umar Farooq
Umar Farooq

Reputation: 331

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

If an ArrayList works, this is how I'd do it.

Upvotes: -1

Related Questions