Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a two Dimensional ArrayList in java with Integers?

Tags:

java

arraylist

I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I'm not sure how to initialize such an array or store information.

Say I have the following data

   0 connects 1
   2 connects 3 
   4 connects 5

....etc up to a vast amount of random connections

and I want to insert

true(1) into [0][1], 
true(1) into [2][3], 
true(1) into [4][5]. 

Can the array automatically update the column/rows for me

Any help is appreciated thanks

like image 621
xiao Avatar asked Feb 16 '11 22:02

xiao


People also ask

How do you add values to a two-dimensional ArrayList in Java?

<ArrayList_name>. add(Object element) : It helps in adding a new row in our existing 2D arraylist where element is the element to be added of datatype of which ArrayList created. <ArrayList_name> . add(int index, Object element) : It helps in adding the element at a particular index.

How do you fill a double array in Java?

Elements can be filled in a Java double array in a specified range using the java. util. Arrays. fill() method.


1 Answers

I'm not sure how to initialize such an array or store information.

Like this for instance:

List<List<Integer>> twoDim = new ArrayList<List<Integer>>();

twoDim.add(Arrays.asList(0, 1, 0, 1, 0));
twoDim.add(Arrays.asList(0, 1, 1, 0, 1));
twoDim.add(Arrays.asList(0, 0, 0, 1, 0));

or like this if you prefer:

List<List<Integer>> twoDim = new ArrayList<List<Integer>>() {{
    add(Arrays.asList(0, 1, 0, 1, 0));
    add(Arrays.asList(0, 1, 1, 0, 1));
    add(Arrays.asList(0, 0, 0, 1, 0));
}};

To insert a new row, you do

twoDim.add(new ArrayList<Integer>());

and to append another element on a specific row you do

twoDim.get(row).add(someValue);

Here is a more complete example:

import java.util.*;

public class Test {

    public static void main(String[] args) {

        List<List<Integer>> twoDim = new ArrayList<List<Integer>>();

        String[] inputLines = { "0 1 0 1 0", "0 1 1 0 1", "0 0 0 1 0" };

        for (String line : inputLines) {
            List<Integer> row = new ArrayList<Integer>();

            Scanner s = new Scanner(line);
            while (s.hasNextInt())
                row.add(s.nextInt());

            twoDim.add(row);
        }
    }
}
like image 176
aioobe Avatar answered Oct 12 '22 05:10

aioobe