java list 只返回最后一个元素 [英] java list returning last element only

查看:118
本文介绍了java list 只返回最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pojo where I am trying to read data from a csv file into a list and then print it back out. Reading from the file is working fine and at the instant of read/add, I can see the right Id is getting picked up, but once I try to print it all back, I get only the last element of the list. Below is what I am trying:

    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<Team> teams = new ArrayList<Team>();
    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());
    }

}

我从上面得到的输出是:

The output that I get from above is:

团队 ID 为:1

团队 ID 为:2

团队 ID 为:3

团队 ID 是:4

团队信息:4

团队信息:4

团队信息:4

团队信息:4

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

What am I missing..? Why are the first 3 elements getting lost..?

推荐答案

您在循环之前只创建了一个 Team 对象.你不断用读取的条目替换它的内容,所以它只代表最后一行.然后,您已经用同一个对象多次填充了列表.在循环内创建团队.

You created only one Team object before the loop. You keep replacing its content with the read entries, so it represents only the last row. You have then list filled multiple times with the same object. Create team inside the loop.

这篇关于java list 只返回最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆