我想在二维数组中添加动态项,
现在我有了如下所示的数组,
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}。您能给我建议一个想法吗?提前致谢。
最佳答案
如果我正确理解您的问题,您需要执行以下步骤:
创建一个数字数组:
String[] numbers = {"One", "Two", "Three", ...};
循环遍历这个数组并检查索引是否为偶数,使用Boolean.TRUE
,否则使用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], ...]
<小时/>
但这不是存储值的更好方法,相反,您可以创建自己的对象,它可以有两个参数 String 和 Boolean :
class MyObject{
String n;
Boolean;
...
}
关于java - 无法在java中的二维数组中动态项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47028344/