创建初始重复数据的二维字符串数组的最有效方法是什么? [英] What is the most efficient way to create a 2d string array of initally repetitive data?

查看:49
本文介绍了创建初始重复数据的二维字符串数组的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,通常为了定义所述游戏板,我将使用以下代码:

In Python, typically to define said game board I would have used the following code:

board = [['0','0','0','0','0','0','0','0','0','0'] for i in range(10)]

但是,到目前为止,我一直只能使用Java来产生相同的结果:

However, using Java the only way I have been able to find so far to produce the same result would be to do:

public static String[][] board = {
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"},
        {"0","0","0","0","0","0","0","0","0","0"}};

当然,必须有一种更有效的方法来执行此操作.我知道如果它是整数,我可以有效地做到这一点,但考虑到这种情况,它必须是字符串.我以为for循环也可以应用,但是我似乎找不到合适的语法.也许不适用于Java.有什么建议吗?

Surely there must be a more efficient way of doing this. I know I can do it efficiently if it were to be integers, but it has to be strings given the situation. I had thought a for loop would also have applied, but I can't seem to find the right syntax for it; perhaps it isn't applicable for Java. Are there any suggestions?

推荐答案

您可以遍历每行并使用

You can loop over each row and use Arrays.fill:

public static String[][] board = new String[rows][cols];
static {
    for (String[] row : board) Arrays.fill(row, "0");
}

演示

这篇关于创建初始重复数据的二维字符串数组的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆