Java List不断添加最后一条记录,并将其复制为文件中的记录数

Hor*_*ice 5 java arraylist

我的代码中发生了一件奇怪的事情,我只是不确定它们是怎么回事.我有一个看起来像这样的文件:

id;state;city;total_pop;avg_temp
1;Florida;;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;;34
Run Code Online (Sandbox Code Playgroud)

我的java解析器应该创建一个map列表作为结果并返回.但唯一返回的是文件中为文件中的行数重复的最后一条记录.有人可以关注我的代码,并告诉我发生了什么事吗?先感谢您.

public class FileParserUtil {

    public List<Map<String, String>> parseFile(String fileName, char seperator)
            throws IOException {

        CSVReader reader = new CSVReader(new FileReader(fileName), seperator);
        Map<String, String> record = new HashMap<String, String>();
        List<Map<String, String>> rows = new ArrayList<Map<String, String>>();

        String[] header = reader.readNext();
        String[] nextLine;

        while ((nextLine = reader.readNext()) != null) {
            for (int i = 0; i < header.length; i++) {
                record.put(header[i], nextLine[i]);
            }
            System.out.println("--------Here is the record: ---------");
            System.out.println(record);
            rows.add(record);
            System.out.println("--------Here are the rows: ---------");
            System.out.println(rows);
        }
        reader.close();
        return rows;

    }
}
Run Code Online (Sandbox Code Playgroud)

这是从主方法运行上面的控制台输出...

--------Here is the record: ---------
{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}
--------Here are the rows: ---------
[{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}]
--------Here is the record: ---------
{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}
--------Here are the rows: ---------
[{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}, {id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}]
--------Here is the record: ---------
{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}
--------Here are the rows: ---------
[{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}]
Run Code Online (Sandbox Code Playgroud)

Thi*_*thi 2

这是因为在 HashMap 中你不能有重复的值..所以,当你这样做时

record.put("id","1");
Run Code Online (Sandbox Code Playgroud)

它将检查是否已经存在名为“id”的键,如果存在,它将用新值替换其旧值。在第一次迭代时,它不会替换任何内容,但从下一次迭代开始,它将开始替换旧值。

当你添加

row.add(record);
Run Code Online (Sandbox Code Playgroud)

您一次又一次地添加相同的引用,并且由于映射仅包含新插入的值,因此toString()调用相同引用的方法并一次又一次地打印相同的值。

你应该添加

record = new HashMap<String,String>();
Run Code Online (Sandbox Code Playgroud)

为每条记录添加一个新地图。