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?
ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.
ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it. ArrayList is part of Java's collection framework and implements Java's List interface.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
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.
BTW. you should prefer coding against an Interface.
private ArrayList<String[]> action = new ArrayList<String[]>();
Should be
private List<String[]> action = new ArrayList<String[]>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With