我的代码中发生了一件奇怪的事情,但我不确定是怎么回事。我有一个看起来像这样的文件:
id;state;city;total_pop;avg_temp
1;Florida;;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;;34
我的Java解析器应创建一个地图列表作为结果并返回。但是唯一返回的是文件中的最后一条记录,重复了文件中的行数。有人可以看我的代码并启发我发生了什么吗?先感谢您。
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;
}
}
这是上面从主要方法运行的控制台输出...
--------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}]
这是因为在HashMap中您不能有重复的值..因此,当您执行此操作时
record.put("id","1");
它将检查是否已经有一个名为“ id”的键,如果存在,它将用新值替换其旧值。在第一个迭代中,它不会替换任何内容,但是从下一个迭代中,它将开始替换旧值。
当您添加
row.add(record);
您将一次又一次添加相同的引用,并且由于映射仅包含新插入的值,因此toString()
将调用相同引用的方法,并且一次又一次打印相同的值。
你应该添加
record = new HashMap<String,String>();
为每个记录添加一个新地图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句