[java] Two dimensional array list

I've heard of using a two dimensional array like this :

String[][] strArr;

But is there any way of doing this with a list?

Maybe something like this?

ArrayList<String><String> strList;

And using something like this to add to it?

strList.add("hey", "hey");

Any way of doing something like this? Any help appreciated.

It would be good if there is because i am currently putting strings into two differrent ArrayList's in pairs.

This question is related to java

The answer is


You can create a list,

ArrayList<String[]> outerArr = new ArrayList<String[]>(); 

and add other lists to it like so:

String[] myString1= {"hey","hey","hey","hey"};  
outerArr .add(myString1);
String[] myString2= {"you","you","you","you"};
outerArr .add(myString2);

Now you can use the double loop below to show everything inside all lists

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

   String[] myString= new String[4]; 
   myString=outerArr.get(i);
   for(int j=0;j<myString.length;j++){
      System.out.print(myString[j]); 
   }
   System.out.print("\n");

}

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

Declaring a two dimensional ArrayList:

ArrayList<ArrayList<String>> rows = new ArrayList<String>();

Or

ArrayList<ArrayList<String>> rows = new ArrayList<>();

Or

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(); 

All the above are valid declarations for a two dimensional ArrayList!

Now, Declaring a one dimensional ArrayList:

ArrayList<String> row = new ArrayList<>();

Inserting values in the two dimensional ArrayList:

for(int i=0; i<5; i++){
    ArrayList<String> row = new ArrayList<>();
    for(int j=0; j<5; j++){
        row.add("Add values here"); 
    }
    rows.add(row); 
}

fetching the values from the two dimensional ArrayList:

for(int i=0; i<5; i++){
    for(int j=0; j<5; j++){
        System.out.print(rows.get(i).get(j)+" ");
     }
     System.out.println("");
}

A 2d array is simply an array of arrays. The analog for lists is simply a List of Lists.

ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.


If your platform matrix supports Java 7 then you can use like below

List<List<String>> myList = new ArrayList<>();

I know that's an old question with good answers, but I believe I can add my 2 cents.

The simplest and most flexible way which works for me is just using an almost "Plain and Old Java Object" class2D to create each "row" of your array.

The below example has some explanations and is executable (you can copy and paste it, but remember to check the package name):

package my2darraylist;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;

public class My2DArrayList
{
    public static void main(String[] args)
    {
        // This is your "2D" ArrayList
        // 
        List<Box> boxes = new ArrayList<>();

        // Add your stuff
        //
        Box stuff = new Box();
        stuff.setAString( "This is my stuff");
        stuff.addString("My Stuff 01");
        stuff.addInteger( 1 );
        boxes.add( stuff );

        // Add other stuff
        //
        Box otherStuff = new Box();
        otherStuff.setAString( "This is my other stuff");
        otherStuff.addString("My Other Stuff 01");
        otherStuff.addInteger( 1 );
        otherStuff.addString("My Other Stuff 02");
        otherStuff.addInteger( 2 );
        boxes.add( otherStuff );

        // List the whole thing
        for ( Box box : boxes)
        {
            System.out.println( box.getAString() );
            System.out.println( box.getMyStrings().size() );
            System.out.println( box.getMyIntegers().size() );
        }
    }

}

class Box
{
    // Each attribute is a "Column" in you array
    //    
    private String aString;
    private List<String> myStrings = new ArrayList<>() ;
    private List<Integer> myIntegers = new ArrayList<>();
    // Use your imagination...
    //
    private JPanel jpanel;

    public void addString( String s )
    {
        myStrings.add( s );
    }

    public void addInteger( int i )
    {
        myIntegers.add( i );
    }

    // Getters & Setters

    public String getAString()
    {
        return aString;
    }

    public void setAString(String aString)
    {
        this.aString = aString;
    }

    public List<String> getMyStrings()
    {
        return myStrings;
    }

    public void setMyStrings(List<String> myStrings)
    {
        this.myStrings = myStrings;
    }

    public List<Integer> getMyIntegers()
    {
        return myIntegers;
    }

    public void setMyIntegers(List<Integer> myIntegers)
    {
        this.myIntegers = myIntegers;
    }

    public JPanel getJpanel()
    {
        return jpanel;
    }

    public void setJpanel(JPanel jpanel)
    {
        this.jpanel = jpanel;
    }
}

UPDATE - To answer the question from @Mohammed Akhtar Zuberi, I've created the simplified version of the program, to make it easier to show the results.

import java.util.ArrayList;

public class My2DArrayListSimplified
{

    public static void main(String[] args)
    {
        ArrayList<Row> rows = new ArrayList<>();
        Row row;
        // Insert the columns for each row
        //             First Name, Last Name, Age
        row = new Row("John",      "Doe",     30);
        rows.add(row);
        row = new Row("Jane",      "Doe",     29);
        rows.add(row);
        row = new Row("Mary",      "Doe",      1);
        rows.add(row);

        // Show the Array
        //
        System.out.println("First\t Last\tAge");
        System.out.println("----------------------");
        for (Row printRow : rows)
        {
            System.out.println(
                    printRow.getFirstName() + "\t " +
                    printRow.getLastName() + "\t" +
                    printRow.getAge());

        }
    }

}

class Row
{

    // REMEMBER: each attribute is a column
    //
    private final String firstName;
    private final String lastName;
    private final int age;

    public Row(String firstName, String lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public int getAge()
    {
        return age;
    }

}

The code above produces the following result (I ran it on NetBeans):

run:
First    Last   Age
----------------------
John     Doe    30
Jane     Doe    29
Mary     Doe    1
BUILD SUCCESSFUL (total time: 0 seconds)

Infact, 2 dimensional array is the list of list of X, where X is one of your data structures from typical ones to user-defined ones. As the following snapshot code, I added row by row into an array triangle. To create each row, I used the method add to add elements manually or the method asList to create a list from a band of data.

package algorithms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RunDemo {

/**
 * @param args
 */
public static void main(String[] args) {
    // Get n
    List<List<Integer>> triangle = new ArrayList<List<Integer>>();

    List<Integer> row1 = new ArrayList<Integer>(1);
    row1.add(2);
    triangle.add(row1);

    List<Integer> row2 = new ArrayList<Integer>(2);
    row2.add(3);row2.add(4);
    triangle.add(row2);

    triangle.add(Arrays.asList(6,5,7));
    triangle.add(Arrays.asList(4,1,8,3));

    System.out.println("Size = "+ triangle.size());
    for (int i=0; i<triangle.size();i++)
        System.out.println(triangle.get(i));

}
}

Running the sample, it generates the output:

Size = 4
[2]
[3, 4]
[6, 5, 7]
[4, 1, 8, 3]

Here's how to make and print a 2D Multi-Dimensional Array using the ArrayList Object.

import java.util.ArrayList;

public class TwoD_ArrayListExample {
    static public ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();

    public static void main(String[] args) {
        insertObjects();
        printTable(gameBoard);
    }

    public static void insertObjects() {
        for (int rowNum = 0; rowNum != 8; rowNum++) {
            ArrayList<String> oneRow = new ArrayList<String>();
            gameBoard.add(rowNum, oneRow);

            for (int columnNum = 0; columnNum != 8; columnNum++) {
                String description= "Description of Objects: row= "+ rowNum + ", column= "+ columnNum;
                    oneRow.add(columnNum, description);
            }
        }
    }

    // The printTable method prints the table to the console
    private static void printTable(ArrayList<ArrayList<String>> table) {
        for (int row = 0; row != 8; row++) {
            for (int col = 0; col != 8; col++) {
                System.out.println("Printing:               row= "+ row+ ", column= "+ col);
                System.out.println(table.get(row).get(col).toString());
            }
        }
        System.out.println("\n");
    }
}