Can I create an array like this in java???
Array
([0]
array
[items1] = "one"
[items2] = "two"
[items3] = "three")
([1]
array
[items1] = "one###"
[items2] = "two###"
[items3] = "three#")
Thanx for your help
Yes, you can do this by creating an array of arrays. For example:
String[][] twoDimensionalPrimitiveArray = {
{"one", "two", "three"},
{"one###", "two###", "three###"}
};
You can also do this with the collection types:
List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));
// ...
private static List<String> createList(String... values) {
List<String> result = new ArrayList<>();
for (String value : values) {
result.add(value);
}
return result;
}
Edit
@immibis has rightly pointed out in the comments that createList() can be written more simply as new ArrayList(Arrays.asList(values)).
createList: {return new ArrayList<>(Arrays.asList(value));}`Yes, you can define an array of arrays:
String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
arrayOfArrays[0] = new String[3]; // initialize first array
arrayOfArrays[1] = new String[3]; // initialize second array
// fill arrays
arrayOfArrays[0][0] = "one";
arrayOfArrays[0][1] = "two";
arrayOfArrays[0][2] = "three";
arrayOfArrays[1][0] = "one###";
arrayOfArrays[1][1] = "two###";
arrayOfArrays[1][2] = "three#";
And to test it (print values):
for (String[] array : arrayOfArrays) {
for (String s : array) {
System.out.print(s);
}
System.out.println();
}
For two dimension arrays in Java you can create them as follows:
// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};
Alternatively you can define the array and then fill in each element but that is more tedious, however that may suit your needs more.
// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";