Is there a simple way to create a 2-d collection?
Asked
Active
Viewed 382 times
1
-
1Please improve the question by being more specific. – LJNielsenDk Aug 23 '15 at 19:37
-
http://stackoverflow.com/help/how-to-ask – MattAllegro Aug 23 '15 at 19:40
-
Please tell me how to be specific I will edit it – Zingoflife Aug 23 '15 at 20:24
-
Related (maybe even duplicate) http://stackoverflow.com/questions/32151775/how-can-i-make-a-map-with-two-indexes – Marco13 Aug 23 '15 at 20:37
2 Answers
2
A two-dimensional collection is essentially having lists within a list. For example, to create a 2D ArrayList of strings, you would do something like this:
ArrayList<ArrayList<String>> stringList = new ArrayList<ArrayList<String>>();
To add a new row, you would simply add a new ArrayList:
stringList.add(new ArrayList<String>());
And here's how to add an element to the first row:
stringList.get(0).add("example string");

deezy
- 1,480
- 1
- 11
- 22
-
-
2@Zingoflife: Why would you want to? That doesn't sound very type safe to me. Usually, when one uses a collection, one has an idea about what objects should go into it. Tell us more about the problem you want to solve. As it stands, your question is too broad for any answer to be helpful for a particular problem. – scottb Aug 23 '15 at 20:29
-
@scottb Agreed, also it's impossible to use int with ArrayLists because it is a primitive type. – deezy Aug 23 '15 at 20:33
0
A 2d collection is a bit abstract... what do you mean? A double entry array is a 2d collection.
Why don't you use Multimaps from Guava library? https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained , Those collections ads everything that the jdk is missing for dealing with 2d collections.

Loic
- 1,088
- 7
- 19