Johan Johan - 1 year ago 59
Java Question

Java: ArrayList of String Arrays

I would like to do something like this:

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

...this does not seem to work. Whats the easiest way of storing multiple addresses with 3 fields per address in an array without creating a separate class for it?

Answer Source

Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();

Then you can have:

ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");


(I think some strange things can happen with type erasure here, but I don't think it should matter here)

If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:

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


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

will work.