I'm fairly new to ArrayLists anyway but I need them for this project I'm doing so if you guys could help me I would be more than grateful!
Basically, I need to create a multidemensional ArrayList to hold String values. I know how to do this with a standard array, like so public static String[][] array = {{}}
but this is no good because I don't know the size of my array, all I know is how many demensions it will have.
So, if you guys know how to make a 'dynamically resizable array with 2/+ demensions', please could you tell me.
Thanks In advance,
Andy
Edit/Update
Maybe it would be easier to resize or define a standard array using a varible? But I don't know?
It's probably easier to use my original idea of an ArrayList though... All I need is a complete example code to create a 2D ArrayList and add so example values to both dimensions without knowing the index.
Once I required 2-D arrayList and I created using List and ArrayList and the code is as follows:
Output:
1 2 3
4 5 6
7 8 9
Source : https://www.codepuran.com/java/2d-matrix-arraylist-collection-class-java/
If you're allowed to use predefined Java classes, you could do something like:
Then you can add new elements, something like:
Hope you can understand what I mean and what's going on. Also, you'll need to import java.util.ArrayList; for this, if you're making use of the Java class.
What would you think of this for 3D ArrayList - can be used similarly to arrays - see the comments in the code:
And here is a test code:
Result output:
You can have ArrayList with elements which would be ArrayLists itself.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
Depending on your requirements, you might use a Generic class like the one below to make access easier:
Wouldn't
List<ArrayList<String>> 2dlist = new ArrayList<ArrayList<String>>();
be a better (more efficient) implementation?