【问题标题】:How to create Arraylist with 3 columns (Java)?如何创建具有 3 列的 Arraylist(Java)?
【发布时间】:2015-09-05 21:16:09
【问题描述】:

我需要一些帮助,我是 java 新手,所以可能我需要更改很多东西。我得到了这个结果:

[Goya, Scoop 2000 W, 123]

如果我尝试添加更多,它会显示:

[HMI, Scoop 2000 W, 123]
[HMI, Scoop 2000 W, 123, Fresnel, Set light 1000 W De Sisti, 124]
[HMI, Scoop 2000 W, 123, Fresnel, Set light 1000 W De Sisti, 124, Goya, Set light 1000 W De Sisti, 456]

而我真正需要的是这样的:

[HMI, Scoop 2000 W, 123,]
[Fresnel, Set light 1000 W De Sisti, 124]
[Goya, Set light 1000 W De Sisti, 456]

这是我的代码:

Component[] componente = painelMain.getComponents();
    list = new ArrayList();
    for (int i = 0; i < componente.length; i++) {
        if (componente[i] instanceof JTextField) {
            JTextField textfield = (JTextField) componente[i];
            if (!"".equals(textfield.getText())) {
                list.add(textfield.getText());
                System.out.println(list);
            }
        } else if (componente[i] instanceof JComboBox) {
            JComboBox combo = (JComboBox) componente[i];
            if (!"".equals(combo.getSelectedItem())) {
                list.add(combo.getSelectedItem());
            }
        }
    }
}

【问题讨论】:

  • 他想要一个矩阵而不是一个平面列表
  • 听起来你应该创建一个新类型来表示三个值的组合......(我们目前无法真正说出它们的含义......)

标签: java multiple-columns


【解决方案1】:

你想要的是一个矩阵。您可以使用String[][] 类型的数组或List&lt;List&lt;String&gt;&gt; 类型的列表。

我还简化了您的代码(使用泛型,排除了逻辑),但是所有这些强制转换和 intanceof 可能是您应该改进的糟糕设计的标志。

Component[] components = painelMain.getComponents();
List<List<String> list = new ArrayList<>();
List<String> line;

int i = 0, numCols = 3;
for (Component component : components) {
    if (i % numCols == 0) {
        line = new ArrayList<>();
        list.add(line);
    }
    String content = "";
    if (component instanceof JTextField) {
        content = ((JTextField) component).getText();            
    } else if (component instanceof JComboBox) {
        content = ((JComboBox<String>) component).getSelectedItem();
    }

    if (!content.isEmpty()) {
        line.add(content);
    }
    i = (i + 1) % 3;
}

如果其中一个字符串为空,则存在边缘情况,我不知道您想如何处理它。

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多