简体   繁体   中英

How to create and initialise in Java an array of String arrays in one line?

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.

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.

these two are right too String[][] array = {emptyArr, filledArr, moreFilledArr};

String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};

please do check these tooDocs 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

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM