Let's say I have in Java 8 the following objects defined:
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Now I want to create an array containing these two string arrays. How do I write this?
I tried:
String[][] = {emptyArr, filledArr, moreFilledArr};
This doesn't work. Then I tried:
(String[])[] = {emptyArr, filledArr, moreFilledArr};
With the brackets in the second version I want to indicate that the array is one of string arrays and not a two-dimensional array. Still no success.
What's the correct way to do it? Is there one? Or do I have to resort to ImmutableList
to create an immutable data-structure here.
CodePudding user response:
You have forgotten to give the variable a name? Both of these work.
String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
I recommend you to go through the basic Java syntax specification and tutorials. Start with The Java Tutorials by Oracle Corp, free of cost.
CodePudding user response:
these two are right too String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
please do check these too
Docs for Array in Java Have a Look for more clarification
tutorial of array with java docs
,
I had to add this as a comment but I couldn't, I want to extend with more resources mentioned above , Thanks
CodePudding user response:
We can also achieve it by initialising and assigning to a single dimensional array of type Object. Something like below.
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Object[] newArr = {filledArr, moreFilledArr, emptyArr};
If you want to print the values inside this newArr, then you shall use the below code.
for (int i=0;i< newArr.length; i ){
Arrays.stream(((String[]) newArr[i])).forEach(System.out::println);
}