java list仅返回最后一个元素

我有一个pojo,我试图将csv文件中的数据读入列表,然后将其打印出来。 从文件中读取工作正常,在读取/添加的瞬间,我可以看到正确的ID被拾取,但是一旦我尝试将其全部打印回来,我只得到列表的最后一个元素。 以下是我的尝试:

public static void main(String[] args) throws IOException, ParseException{ Charset charset = Charset.forName("UTF-8"); File dir = new File("/Users/vinnar/eclipse_keplar/workspace/vinnar-pojo-projects/src/com/vinnar/pojo/csvfiles"); File file = null; file = new File(dir.getCanonicalPath() + File.separator + "Teams.csv"); FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis, charset)); String line = null; Team team = new Team(); List teams = new ArrayList(); String csvSeperator = ","; while ((line=br.readLine()) != null){ String[] t = line.split(csvSeperator); System.out.println("Team ID is: " + t[0]); team.setId(Integer.parseInt(t[0])); team.setName(t[1]); team.setRank(Integer.parseInt(t[2])); team.setLstUpdUser(t[3]); DateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH); team.setLstUpdTime((Date) dateFormat.parse(t[4])); teams.add(team); } br.close(); for(Team t1:teams){ System.out.println("Team info: " + t1.getId()); } } 

我从上面得到的输出是:

团队ID是:1

团队ID是:2

团队ID是:3

团队ID是:4

球队信息:4

球队信息:4

球队信息:4

球队信息:4

我错过了什么..? 为什么前3个元素会丢失..?

您在循环之前只创建了一个Team对象。 您继续用读取条目替换其内容,因此它仅代表最后一行。 然后,您使用相同的对象多次填充列表。 在循环内创建团队。

这是因为你在循环中添加相同的对象,而是应该在循环中创建对象以将其添加到列表中:

 Team team; while ((line=br.readLine()) != null){ team = new Team();//new object teams.add(team);//added to list ... }