Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 677
Johan Avatar asked Dec 17 '09 11:12

Johan


People also ask

Can you have an ArrayList of arrays?

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 be a String?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.


2 Answers

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"); singleAddress.add("Makebelieveland");  addresses.add(singleAddress); 

(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]>(); 

to

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

will work.

like image 127
Grundlefleck Avatar answered Sep 21 '22 05:09

Grundlefleck


List<String[]> addresses = new ArrayList<String[]>(); String[] addressesArr  = new String[3];  addressesArr[0] = "zero"; addressesArr[1] = "one"; addressesArr[2] = "two";  addresses.add(addressesArr); 
like image 37
Upul Bandara Avatar answered Sep 22 '22 05:09

Upul Bandara