首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建具有3列(Java)的Arraylist?

如何创建具有3列(Java)的Arraylist?
EN

Stack Overflow用户
提问于 2015-09-05 21:16:09
回答 1查看 2.1K关注 0票数 0

我需要一些帮助,我是刚接触java的,所以我可能需要改变很多东西。我的结果是:

代码语言:javascript
复制
[Goya, Scoop 2000 W, 123]

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

代码语言:javascript
复制
[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]

我真正需要的是这样的东西:

代码语言:javascript
复制
[HMI, Scoop 2000 W, 123,]
[Fresnel, Set light 1000 W De Sisti, 124]
[Goya, Set light 1000 W De Sisti, 456]

这是我的代码:

代码语言:javascript
复制
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());
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-05 21:21:49

你想要的是矩阵。可以使用String[][]类型的数组,也可以使用类型List<List<String>>的列表。

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

代码语言:javascript
复制
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;
}

如果其中一个字符串空了,我不知道你想怎么处理它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32417747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档