user1413969
user1413969

Reputation: 1291

Weird bug with a simple for loop

I'm currently trying to read this XML file (Note that I simplified the XML for simplicities sake):

<Users>
<User id="1" name="NY-01" location="New York">
<Hosts>
    <Host>
       <Host_Name>val9</Host_Name>
    </Host>
    <Host>
       <Host_Name>td8</Host_Name>
    </Host>
</Hosts>
</User>
</Users>

I used the JAXB library to read it.

So essentially I did a loop:

List<DataVal> l = new ArrayList<DataVal>();

for (int i = 0; i < data.getUsers().size(); i++) {
    DataVal pc = new DataVal();
    pc.setUser_id(data.getUsers().get(i).getId().toString());
    pc.setUser_name(data.getUsers().get(i).getName());
    pc.setUser_location(data.getUsers().get(i).getLocation());

    for (int j = 0; j < data.getUsers().get(i).getHosts().getHost().size(); j++) {
        pc.setHost_name(data.getUsers().get(i).getHosts().getHost().get(j).getHostName());
        System.out.println(pc);
        l.add(pc);
    }
}   

Note that when I do the System.out.println(pc) right before adding to the list, the value for pc is correct;

But when I print the ArrayList "l" after this block of code, I'm getting the host_name td8 both times instead of val9 and td8 as the next one. The id, name, location values are correct though.

Why is this?

This is the code for printing the list:

for (int q = 0; q < l.size(); q++) {
    System.out.println(l.get(q)); // I have a toString implementation of this...
}

Edit: After debugging this with eclipse, for some reason after each iteration of the j loop, the values all change to the last loop value for host_name...

Upvotes: 0

Views: 68

Answers (1)

P. Lalonde
P. Lalonde

Reputation: 694

Seems like your are replacing pc.setHost_name on every pass, this means that your host name value will be equal to the last reading of a host.

If they need to be distinct, this means that you need to create your DataVal object inside the host loop, not the user loop.

Upvotes: 2

Related Questions