Java ArrayList of Arrays?

139,262

Solution 1

Should be

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...

You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you.

A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant.

Solution 2

BTW. you should prefer coding against an Interface.

private ArrayList<String[]> action = new ArrayList<String[]>();

Should be

private List<String[]> action = new ArrayList<String[]>();

Solution 3

Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach.

Code:

Since Java doesn't supply a Pair class, you'll need to define your own.

class Pair<A, B> {
  public final A first;
  public final B second;

  public Pair(final A first, final B second) {
    this.first = first;
    this.second = second;
  }

  //
  // Override 'equals', 'hashcode' and 'toString'
  //
}

and then use it as:

List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();

[ Here I used List because it's considered a good practice to program to interfaces. ]

Solution 4

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

Don't need String[2];

Solution 5

As already answered, you can create an ArrayList of String Arrays as @Péter Török written;

    //Declaration of an ArrayList of String Arrays
    ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

When assigning different String Arrays to this ArrayList, each String Array's length will be different.

In the following example, 4 different Array of String added, their lengths are varying.

String Array #1: len: 3
String Array #2: len: 1
String Array #3: len: 4
String Array #4: len: 2

The Demonstration code is as below;

import java.util.ArrayList;

public class TestMultiArray {

    public static void main(String[] args) {
        //Declaration of an ArrayList of String Arrays
        ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

        //Assignment of 4 different String Arrays with different lengths
        listOfArrayList.add( new String[]{"line1: test String 1","line1: test String 2","line1: test String 3"}  );
        listOfArrayList.add( new String[]{"line2: test String 1"}  );
        listOfArrayList.add( new String[]{"line3: test String 1","line3: test String 2","line3: test String 3", "line3: test String 4"}  );
        listOfArrayList.add( new String[]{"line4: test String 1","line4: test String 2"}  );

        // Printing out the ArrayList Contents of String Arrays
        // '$' is used to indicate the String elements of String Arrays
        for( int i = 0; i < listOfArrayList.size(); i++ ) {
            for( int j = 0; j < listOfArrayList.get(i).length; j++ )
                System.out.printf(" $ " + listOfArrayList.get(i)[j]);

            System.out.println();
        }

    }
}

And the output is as follows;

 $ line1: test String 1 $ line1: test String 2 $ line1: test String 3
 $ line2: test String 1
 $ line3: test String 1 $ line3: test String 2 $ line3: test String 3 $ line3: test String 4
 $ line4: test String 1 $ line4: test String 2

Also notify that you can initialize a new Array of Sting as below;

new String[]{ str1, str2, str3,... }; // Assuming str's are String objects

So this is same with;

String[] newStringArray = { str1, str2, str3 }; // Assuming str's are String objects

I've written this demonstration just to show that no theArrayList object, all the elements are references to different instantiations of String Arrays, thus the length of each String Arrays are not have to be the same, neither it is important.

One last note: It will be best practice to use the ArrayList within a List interface, instead of which that you've used in your question.

It will be better to use the List interface as below;

    //Declaration of an ArrayList of String Arrays
    List<String[]> listOfArrayList = new ArrayList<String[]>();
Share:
139,262

Related videos on Youtube

Rumpleteaser
Author by

Rumpleteaser

Updated on July 09, 2022

Comments

  • Rumpleteaser
    Rumpleteaser almost 2 years

    I want to create a mutli dimensional array without a fixed size.

    I need to be able to add items of String[2] to it.

    I have tried looking at:

    private ArrayList<String[]> action = new ArrayList<String[2]>();
    

    but that doesn't work. does anyone have any other ideas?

  • dsmith
    dsmith over 13 years
    +1 agreed. Also, it should usually be declared final. There are very few use cases for rebinding a container variable.
  • dsmith
    dsmith over 13 years
    +1 I was just about to give the exact same answer. There as been much debate about whether a java.util.Pair class is needed. I think yes.
  • missingfaktor
    missingfaktor over 13 years
    @athena: See the first question and its answer in this Erich Gamma interview: goo.gl/fz9G
  • whaley
    whaley over 13 years
    Agreed to an extent - a Pair class that you have provided is a great start and is a nice generalization as I find that Collections/Arrays that contain other Collections/Arrays is a code smell. However, in this case, it is quite likely that the two Strings the OP is pairing together probably have some special relationship to each other, and in such case probably deserve a class of their own that specifies that relationship (and contains methods specific to the pair). It could be a subclass of Pair<String,String> of course.
  • emory
    emory over 13 years
    Java has java.util.Map.Pair. No need to define ur own.
  • missingfaktor
    missingfaktor over 13 years
    @emory: It's java.util.Map.Entry. Its name indicates its purpose i.e. serve as a structure to store a key and a value together in a Map. It's not supposed to be used as general purpose structure to store any two elements (which is what Pair is for).