vinnar
vinnar

Reputation: 15

java list returning last element only

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:

Team ID is: 1

Team ID is: 2

Team ID is: 3

Team ID is: 4

Team info: 4

Team info: 4

Team info: 4

Team info: 4

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

Upvotes: 0

Views: 3010

Answers (2)

user2575725
user2575725

Reputation:

It's because your adding the same object within a loop, instead you should create the object within the loop to add it to the list:

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

Upvotes: 1

Zielu
Zielu

Reputation: 8562

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.

Upvotes: 0

Related Questions