-2

How can I generate a 3 by 3 box layout in Java? I can do it hardcode, but I dont know how I will implement it when I use an ArrayList. I also don't know how I will create a 2d array with the use of an Arraylist. This is how I want my code to start:

    for (int i = 0; i<ArrayList.size(); i++){

    some content

    }

Any ideas on how to start

  • Try [this](http://stackoverflow.com/questions/1067073/initialising-a-multidimensional-array-in-java) – Nate Anderson Nov 03 '16 at 17:52
  • the link you showed only shows arrays to their examples. I want to do it using Arraylist. is it possible? – bryxwarrior Nov 03 '16 at 18:05
  • There are lots of answers to your question on SO. Try searching the site more thoroughly. [this was the first result of a site search](http://stackoverflow.com/questions/16956720/how-to-create-an-2d-arraylist-in-java), which is an idea on how to start. – Nate Anderson Nov 03 '16 at 19:27
  • Will do. Thank you for the idea. – bryxwarrior Nov 03 '16 at 21:10

1 Answers1

0

It is possible, with an ArrayList<ArrayList<Integer>>, or any other type than Integer.

Essentially when you look at a multi-dimensional array you have an array of arrays of a certain type. In this case, to populate the array or print 3x3 ArrayList, you would iterate through them like you would with an array:

Given an ArrayList as such: ArrayList<ArrayList<Integer>> box

    for (int i = 0; i < box.size(); i++) {
        for (int j = 0; j < box.get(i).size(); j++) {
            System.out.print(box.get(i).get(j));
        }

        System.out.println();
    }

This is a very simple example. You can also use forEach loops as such:

for (ArrayList<Integer> row: box) {
    for (Integer cell: row) {
        System.out.print(cell);
    }

    System.out.println();
}

Note that initializing the list is a bit trickier with multiple "dimensions":

for (int i = 0; i < 3; i++) {
    box.add(new ArrayList<Integer>());

    for (int j = 0; j < 3; j++) {
        box.get(i).add(...);
    }
}

Keep in mind that this answer uses very simple Java, there is definitely more graceful ways to do it. However, I suspect that this is probably for a homework, hence the type of answer given.

Isabelle Plante
  • 518
  • 3
  • 7
  • 20
  • I will try to implement this example. This is for my thesis. The reason why I asked this in a very simple manner because I cant seem to find questions that are similar to my problem so I made it this way. Thank you – bryxwarrior Nov 03 '16 at 21:09