如何将数据添加到ARRAYLIST

时间:2011-01-01 06:32:53

标签: java swing arraylist jtable

try {
    final List<String> ar = new ArrayList<String>();
    final PRIvariable pri = new PRIvariable();

    final BufferedReader reader = new BufferedReader(
        new InputStreamReader(new FileInputStream("C:/cdr2.csv")));

    while (reader.ready()) {
        final String line = reader.readLine();
        final String[] values = line.split(",");
        pri.dateText = values[2] + "    " + values[4];
        pri.count = pri.count + 1;
        pri.sum = pri.sum + Integer.parseInt(values[7]);
        System.out.println(pri.dateText + "  " + pri.sum + " " + pri.count);
        ar.add(pri);
    }

    final String[] columnNames = { "Date", "TOTAL", "COUNTS" };
    final String[][] cells = new String[ar.size()][3];
    for (int i = 0; i < ar.size(); i++) {
        cells[i][0] = ((PRIvariable) ar.get(i)).dateText;
        cells[i][1] = "" + ((PRIvariable) ar.get(i)).sum;
        cells[i][2] = "" + ((PRIvariable) ar.get(i)).count;
    }
    table = new JTable(cells, columnNames);
    table.setSize(400, 400);
    table.setVisible(true);
    final JScrollPane js = new JScrollPane();
    js.setViewportView(table);
    js.setSize(400, 400);
    js.setVisible(true);
    add(js, java.awt.BorderLayout.CENTER);

} catch (final Exception e) {
    System.out.println(e);
}

这是我的代码。在这里,我想读取文本文件并将该数据放入Jtable。但是在这段代码中,它显示了Jtable的每一行都填充了arraylist(ar)最后一行中包含的相同数据。 (我认为我的arraylist存在问题)。我怎么能解决这个问题......

1 个答案:

答案 0 :(得分:2)

问题在于变量pri。它必须在while循环中创建。

喜欢这个

String line = null;
while ((line = reader.readLine()) != null) {
    PRIvariable pri = new PRIvariable();
    String[] values = line.split(",");
    pri.dateText = values[2] + "    " + values[4];
    pri.count = pri.count + 1;
    pri.sum = pri.sum + Integer.parseInt(values[7]);
    System.out.println(pri.dateText + "  " + pri.sum + " " + pri.count);
    ar.add(pri);
}

在您的代码中,您希望为文件中的每一行创建一个单独的PRIvariable实例,但是您在开头只创建一次PRIvariable实例,那么您始终使用该实例覆盖以前的值。