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:
Create the ArrayList like ArrayList action
.
In JDK 1.5 or higher use ArrayList <string[]>
reference name.
In JDK 1.4 or lower use ArrayList
reference name.
Specify the access specifiers:
Then specify the reference it will be assigned in
action = new ArrayList<String[]>();
In JVM new
keyword will allocate memory in runtime for the object.
You should not assigned the value where declared, because you are asking without fixed size.
Finally you can be use the add()
method in ArrayList. Use like
action.add(new string[how much you need])
It will allocate the specific memory area in heap.
ArrayList<String[]> action = new ArrayList<String[]>();
Don't need String[2]
;
This works very well.
ArrayList<String[]> a = new ArrayList<String[]>();
a.add(new String[3]);
a.get(0)[0] = "Zubair";
a.get(0)[1] = "Borkala";
a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);
Result will be
Borkala
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. ]
BTW. you should prefer coding against an Interface.
private ArrayList<String[]> action = new ArrayList<String[]>();
Should be
private List<String[]> action = new ArrayList<String[]>();
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.