1

Is there a simple way to create a 2-d collection?

Zingoflife
  • 19
  • 2

2 Answers2

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
  • But how would you add string ints and other data types – Zingoflife Aug 23 '15 at 20:04
  • 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