无法在Java中的二维数组中动态生成项目 [英] Could not dynamic items in two dimensions array in java

查看:43
本文介绍了无法在Java中的二维数组中动态生成项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在二维数组中添加动态项,

I want to add dynamic items in two dimension array,

现在我有如下所示的数组,

Now i have have that array like below,

private static final Object[][] DATA = { { "One", Boolean.TRUE }, { "Two", Boolean.FALSE },
            { "Three", Boolean.TRUE }, { "Four", Boolean.FALSE }, { "Five", Boolean.TRUE }, { "Six", Boolean.FALSE },
            { "Seven", Boolean.TRUE }, { "Eight", Boolean.FALSE }, { "Nine", Boolean.TRUE }, { "Ten", Boolean.FALSE },
            { "One", Boolean.TRUE }, { "Two", Boolean.FALSE }, { "Three", Boolean.TRUE }, { "Four", Boolean.FALSE },
            { "Five", Boolean.TRUE }, { "Six", Boolean.FALSE }, { "Seven", Boolean.TRUE }, { "Eight", Boolean.FALSE },
            { "Nine", Boolean.TRUE }, { "Ten", Boolean.FALSE } };

我想添加每个项目,而不是每个项目 { Nine,Boolean.TRUE} 动态地。您能给我建议一个做这个的主意吗?

Instead of this i want to add each item { "Nine", Boolean.TRUE } dynamically. Could you please suggest me an idea to do this? Thanks in advance.

推荐答案

如果我正确理解了您的问题,则需要执行以下步骤:

If i understand your question correctly, you need this steps :

创建数字数组:

String[] numbers = {"One", "Two", "Three", ...};

在该数组上循环并检查索引是否为偶数,使用 Boolean.TRUE 否则使用 Boolean.FALSE

Loop over this array and check if the index in even or not it yes use Boolean.TRUE else use Boolean.FALSE

String[] numbers = {"One", "Two", "Three", ...};
Object[][] data = new Object[numbers.length][];
for (int i = 0; i < numbers.length; i++) {
    if (i % 2 == 0) {
        data[i] = new Object[]{numbers[i], Boolean.TRUE};
    } else {
        data[i] = new Object[]{numbers[i], Boolean.FALSE};
    }
}

如果使用:

System.out.println(Arrays.deepToString(data));

输出为:

[[One, true], [Two, false], [Three, true], ...]






但这不是存储值的更好方法,而是可以创建自己的Object,该Object可以具有两个参数String和Boolean:


But this is not the better way you store values, instead you can create your own Object which can have two parameters String and Boolean :

class MyObject{
   String n;
   Boolean;
   ...
}

这篇关于无法在Java中的二维数组中动态生成项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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