Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList of Arrays?

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?

like image 828
Rumpleteaser Avatar asked Sep 04 '10 12:09

Rumpleteaser


People also ask

Can you have an ArrayList of arrays in Java?

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.

Can an ArrayList store an array?

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.

Which is better array or ArrayList in Java?

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.


2 Answers

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.

like image 142
Péter Török Avatar answered Sep 20 '22 13:09

Péter Török


BTW. you should prefer coding against an Interface.

private ArrayList<String[]> action = new ArrayList<String[]>(); 

Should be

private List<String[]> action = new ArrayList<String[]>(); 
like image 32
daniel Avatar answered Sep 24 '22 13:09

daniel