I need to implement a 2D dynamic array. The number of rows is fixed, say n. But the number of columns for each row is not fixed and equivalent. For instance, the first row has 3 elements and the second row has 5 elements. How to do this in Java using Arraylist. Thanks.
-
Does - in your example - the first row always have 3 elements? If so, why don't you simply create a (e.g.) `Something[][] s = new Something[numRows][]` and `s[0] = new Something[3]`? – Tedil Jun 03 '11 at 20:30
9 Answers
How about List<List<Foo>>
?
For Example:
List<List<Foo>> list = new ArrayList<List<Foo>>();
List<Foo> row1 = new ArrayList<Foo>();
row1.add(new Foo());
row1.add(new Foo());
row1.add(new Foo());
list.add(row1);
List<Foo> row2 = new ArrayList<Foo>();
row2.add(new Foo());
row2.add(new Foo());
list.add(row2);

- 237,923
- 42
- 401
- 438
-
What's the difference between list and ArrayList? Why just ArrayList
> list = new ArrayList – user288609 Jun 03 '11 at 20:48>(); Thanks -
3`List` is an `interface` , `ArrayList` is its specific implementation. well if you have `List
` then you can refer to an `LinkedList` or some other implementation also – jmj Jun 03 '11 at 20:56
ArrayList<ArrayList<SomeObject>> twodlist = new ArrayList<ArrayList<SomeObject>>();
ArrayList<SomeObject> row = new ArrayList<SomeObject>();
row.add(new SomeObject(/* whatever */));
// etc
twodlist.add(row);
row = new ArrayList<SomeObject>();
// etc

- 3,752
- 1
- 23
- 32
You can either use a array for the rows since this dimenstion is fixed:
@SuppressWarnings("unchecked")
ArrayList<T>[] arr = new ArrayList[ fixedsize];
or use nested ArrayLists:
List<List<T>> list = new ArrayList<List<T>>( fixedsize );

- 13,877
- 6
- 48
- 58
-
-
Nope it's not forbidden! You can very well create arrays of parameterized types and you can test my code. It compiles and works as expected. – x4u Jun 03 '11 at 20:46
-
Oops, sorry, you are right I had a error in my code and the cast can be omitted. I now fixed it and it will compile now. – x4u Jun 03 '11 at 21:08
-
aaah yeah, there we go. didn't see that before. can i assume that this is typesafe, considerung the actual variable isn't a raw type? – MarioP Jun 03 '11 at 21:12
-
It's actually more type safe than the generic collection types as it is guaranteed that there will never be an object in the array that is not a instance of the component type of the array. So you can be 100% sure that the array will always contain ArrayList objects (or null) but never a string for instance. A `ArrayList
>` can technically hold any object you like and you can manage to put a string in it although you would need to use some nasty casts or reflection to do this. Apart from that the type safety or lack thereof is the same for arrays and collection types. – x4u Jun 03 '11 at 21:21
Try:
ArrayList<ArrayList<DataType>> array = new ArrayList<ArrayList<DataType>>();
for (int i = 0; i < n; ++i) {
array.add(new ArrayList<DataType>());
}

- 232,168
- 48
- 399
- 521
-
1
-
Correction: you _can_ with `@SuppressWarnings("unchecked")`, but you're discouraged to. – trutheality Jun 03 '11 at 20:37
-
But how to add entries for each ArrayList representing a row? Thanks – user288609 Jun 03 '11 at 20:47
-
@MarioP: What do you mean? Also, see [this answer](http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation/530289#530289) for a full explanation. – trutheality Jun 03 '11 at 20:47
-
@user288609: `array.get(rowNumber).add(element)` (like in my [answer](http://stackoverflow.com/questions/6232257/2d-dynamic-array-using-arraylist-in-java/6232372#6232372)) – trutheality Jun 03 '11 at 20:50
-
@truheality, i cant bring the line `ArrayList
a[] = new ArrayList – MarioP Jun 03 '11 at 20:55[5]` to compile, i can suppress as much warnings as i want. how did you do it? -
@MarioP it has to be done w/o the `
` in the `new` statement. Like so: http://ideone.com/A7fpO – trutheality Jun 03 '11 at 21:09 -
@MarioP - that was an error on my part. I deleted it from my posted answer. – Ted Hopp Jun 03 '11 at 21:37
As you say, you can make an array of arraylists and use the ArrayList(int initial capacity) constructor to set the capacity of each column:
ArrayList<YourObject>[] rows=new ArrayList<YourObjects>[n];
for(i=0;i<n;i++){
rows[i]=ArrayList<YourObjects>(initialsize);
}

- 283
- 1
- 4
- 14
-
1"ArrayList is a raw type. References to generic type ArrayList
should be parameterized" - bad coding style. high risk of `ClassCastException`. – MarioP Jun 03 '11 at 20:36 -
good catch--thanks for the correction! the code above has been fixed. – CodeRedd Jun 04 '11 at 02:50
-
You could create an array of ArrayList elements because your row count is fixed.
ArrayList[] dynamicArray = new ArrayList[n]();
Note: You'll need to allocate an ArrayList object in each entry in the array. So...
for (int loop = 0; loop < n; loop++)
dynamicArray[loop] = new ArrayList();
OR if you'd like both rows and columns to be dynamic you could create an ArrayList of ArrayLists....
ArrayList<ArrayList<T>> dynamicArray = new ArrayList<ArrayList<T>>();
Once again, you'll need to create an array list in each new entry to dynamicArray.

- 3,524
- 2
- 25
- 29
if the number of rows is fixed, try something like this:
ArrayList<MyObject>[] = new ArrayList<MyObject>[fixedRows]

- 681
- 5
- 3
-
-
-
Damn Java generics... Then `ArrayList[] = new ArrayList[fixedRows]`. Suck it Java. – erickzetta Jun 03 '11 at 20:45
-
@erikzetta: it is indeed annoying, I've given up and switched to all-generics when I have cases like that -- the overhead is pretty negligible anyway. – trutheality Jun 03 '11 at 20:55
List<ArrayList<SomeObject>> twoDList = new ArrayList<List<SomeObject>>(n);
for( int i=0; i<n; i++ )
twoDList.add( new ArrayList<SomeObject>() );
Use as:
twoDList.get(rownumber).add(newElementInColumn);

- 23,114
- 6
- 54
- 68
I would create an array of ArrayList (ArrayList[3] rows = new ArrayList[3] if the rows were 3) Then for each row create column classes and insert them into an ArrayList. and then place the ArrayList into the Array. the row array's index can be used to keep track of the row number. Remember arrays start there indexes at 0 so the row number would be rows[index+1]

- 390
- 8
- 20