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?
Following works in Java 8..
List<String[]> addresses = new ArrayList<>();
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr = new String[3];
addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";
addresses.add(addressesArr);
I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:
List<List<String>> addresses = new ArrayList<List<String>>();
But honestly for addresses, I'd create a class to model them.
If you were to use arrays it would be:
List<String[]> addresses = new ArrayList<String[]>();
ie you can't declare the size of the array.
Lastly, don't declare your types as concrete types in instances like this (ie for addresses
). Use the interface as I've done above. This applies to member variables, return types and parameter types.
private List<String[]> addresses = new ArrayList<String[]>();
this will work defenitely...
try this
ArrayList<ArrayList<String>> PriceModelList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceQtyList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceTotalList = new ArrayList<>();
for (int i = 0; i < CustomerNames.length; i++) {
PriceModelList.add(new ArrayList<String>());
String[] PriceModel = {"s6", "s7", "note4", "note5", "j5", "j6"};
for (int j = 0; j < PriceModel.length; j++) {
PriceModelList.get(i).add(PriceModel[j]);
}
PriceQtyList.add(new ArrayList<String>());
String[] PriceQut = {"12", "13", "21", "15", "43", "21"};
for (int k = 0; k < PriceQut.length; k++) {
PriceQtyList.get(i).add(PriceQut[k]);
}
PriceTotalList.add(new ArrayList<String>());
String[] PriceTotal = {"1323", "1312321", "43123212", "43434", "12312", "43322"};
for (int m = 0; m < PriceTotal.length; m++) {
PriceTotalList.get(i).add(PriceTotal[m]);
}
}
ArrayList<ArrayList<ArrayList<String>>> CustomersShoppingLists = new ArrayList<>();
CustomersShoppingLists.add(PriceModelList);
CustomersShoppingLists.add(PriceQtyList);
CustomersShoppingLists.add(PriceTotalList);
You can't force the String arrays to have a specific size. You can do this:
private List<String[]> addresses = new ArrayList<String[]>();
but an array of any size can be added to this list.
However, as others have mentioned, the correct thing to do here is to create a separate class representing addresses. Then you would have something like:
private List<Address> addresses = new ArrayList<Address>();
Source: Stackoverflow.com