Adding blank rows to a 2d array in Java

11,120

Here's a solution with ArrayLists: (test included)

    int[][] ar = new int[][]
        {
        { 0, 1, 2 },
        { 3, 4, 5 },
        { 6, 7, 8 } };
    ArrayList<ArrayList<Integer>> a = new ArrayList<>(ar.length);
    ArrayList<Integer> blankLine = new ArrayList<>(ar.length * 2 - 1);
    for (int i = 0; i < ar.length * 2 - 1; i++)
    {
        blankLine.add(0);
    }

    for (int i = 0; i < ar.length; i++)
    {
        ArrayList<Integer> line = new ArrayList<>();
        for (int j = 0; j < ar[i].length; j++)
        {
            line.add(ar[i][j]);
            if (j != ar[i].length - 1)
                line.add(0);
        }
        a.add(line);
        if (i != ar.length - 1)
            a.add(blankLine);
    }

    for (ArrayList<Integer> b : a)
    {
        System.out.println(b);
    }

Output:

[0, 0, 1, 0, 2]
[0, 0, 0, 0, 0]
[3, 0, 4, 0, 5]
[0, 0, 0, 0, 0]
[6, 0, 7, 0, 8]
Share:
11,120
nobillygreen
Author by

nobillygreen

Updated on June 04, 2022

Comments

  • nobillygreen
    nobillygreen almost 2 years

    Say I have the following 2d array in Java set to a variable named myMap:

    1 3 1
    3 2 3
    1 3 1
    

    The next step in my program is to add rows and columns of zeros as follows:

    1 0 3 0 1
    0 0 0 0 0
    3 0 2 0 3
    0 0 0 0 0
    1 0 3 0 1
    

    Basically, I'm adding arrays of zero into the spaces between the previous rows/columns. I then fill them in with appropriate numbers (irrelevant to my question) and repeat the process (adding more rows/columns of zeros) a finite number of times.

    My question is as follows- what is the easiest and most efficient way to do this in Java? I know I could create a new 2d array and copy everything over, but I feel like there may be a more efficient way to do this. My intuition says that a 2d ArrayList may be the better way to go.

    Also, and this my be important, when my program begins, I DO know what the maximum size this 2d array. Also, I cannot expect the symmetry of the numbers that I put in for this example (these were just put in for a good visual reference).

  • nobillygreen
    nobillygreen over 11 years
    This is beautiful! Thank you so much for the help, Ryan!