简体   繁体   中英

How to initialize a 2D array of strings in java

I know how to declare the array and I have done so:

String[][] board1 = new String[10][10];

Now I want to make it so that every space is "-" by default (without the quotes of course). I have seen other questions like this but the answers didn't make sense to me. All I can understand is that I would probably need a for loop.

The quickest way I can think of is to use Arrays.fill(Object[], Object) like so,

String[][] board1 = new String[10][10];
for (String[] row : board1) {
    Arrays.fill(row, "-");
}
System.out.println(Arrays.deepToString(board1));

This is using a For-Each to iterate the String[] (s) of board1 and fill them with a "-". It then uses Arrays.deepToString(Object[]) to print it.

You could do ...

String[][] board1 = new String[][] {
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
};

or

String[][] board1 = new String[10][10];
for (int outter = 0; outter < board1.length; outter++) {
    String[] row = new String[board1[outter].length];
    for (int inner = 0; inner < row.length; inner++) {
        row[inner] = "-";
    }
    board1[outter] = row;
}

or

String[][] board1 = new String[10][10];
for (int outter = 0; outter < board1.length; outter++) {
    for (int inner = 0; inner < board1[outter].length; inner++) {
        board1[outter][inner] = "-";
    }
}

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