【问题标题】:Strings as an ArrayList and use in another class字符串作为 ArrayList 并在另一个类中使用
【发布时间】:2017-03-20 19:12:54
【问题描述】:

我想在一个数组中获取我的值。稍后我想在另一个类中使用该数组。如何才能做到这一点?

table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    JTable target = (JTable) e.getSource();
                    int row = target.getSelectedRow();
                    int column = target.getSelectedColumn();

                    row = table.convertRowIndexToModel(row);
                    String val1 = (String) table.getModel().getValueAt(row, 0);
                    String val2 = (String) table.getModel().getValueAt(row, 1);
                    String val3 = (String) table.getModel().getValueAt(row, 2);
                    String val4 = (String) table.getModel().getValueAt(row, 3);
                    String val5 = (String) table.getModel().getValueAt(row, 4);

                    System.out.println(val1 + " " + val2 + " " + val3 + " " + val4 + " " + val5);
                }
            }
        }); 

【问题讨论】:

  • 那么,你学会如何使用数组和循环了吗?
  • 您可以尝试查看documentation。至于在另一个类中使用,您可以简单地将数组引用传递给该类。尝试查看here 了解更多详情。
  • 我现在正在学习。我在另一个上下文中使用了一个数组。但在这种情况下,我不确定我应该做什么。任何帮助表示赞赏。

标签: java arrays string arraylist


【解决方案1】:

使用您要添加的值的大小来实例化一个新数组。如果您不知道大小,您应该使用ArrayList

String[] arr = new String[5];

向数组中添加值。你可以把它放在一个循环中,这样代码就不会那么冗长了。

String val1 = (String) table.getModel().getValueAt(row, 0);
arr[0] = val1;

String val2 = (String) table.getModel().getValueAt(row, 1);
arr[1] = val2;

...

然后返回数组

return arr; 

【讨论】:

    【解决方案2】:

    另一种方式,使用集合,它们通常更容易使用:

    List<String> values = new ArrayList<>();
    values.add((String) table.getModel().getValueAt(row, 0))
    ..
    ..
    values.add((String) table.getModel().getValueAt(row, 4););
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多