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?
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.
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.
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.
List<String[]> addresses = new ArrayList<String[]>(); String[] addressesArr = new String[3]; addressesArr[0] = "zero"; addressesArr[1] = "one"; addressesArr[2] = "two"; addresses.add(addressesArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With