Nick Audenaerde
Nick Audenaerde

Reputation: 1025

How to get several values from the same it.next()

List<Drank> dranken = admin.getBestelling().getDranken();
Iterator<Drank> it = dranken.iterator();
while (it.hasNext()) {
     String name = it.next().getName();
     String description = it.next().getDescription();   
     model.addRow(new Object[]{name,description});
}   

This is our code. We want to loop through the array. The problem is that if you use it.next() it always goes to the next value, and because we have getName() and getDescription() it always skips either the name or the description, making value's not match with each other,

any suggestions?

Upvotes: 1

Views: 59

Answers (3)

Joffrey
Joffrey

Reputation: 37680

Use it.next() only once, and get the result in a Drank variable, as @user1906108 shew you.

Alternatively, you can use the enhanced for loop, and totally get rid of the iterator's code:

ArrayList<Drank> dranken = admin.getBestelling().getDranken();

for (Drank d : dranken) {
     String name = d.getName();
     String description = d.getDescription();   
     model.addRow(new Object[]{name,description});
}

Or even shorter, as you don't really need extra variables here:

ArrayList<Drank> dranken = admin.getBestelling().getDranken();

for (Drank d : dranken) {
     model.addRow(new Object[]{ d.getName(), d.getDescription()});
}

Upvotes: 2

BrendanMcKee
BrendanMcKee

Reputation: 846

Change it to this

while (it.hasNext()) {
     Drank item = it.next();
     String name = item.getName();
     String description = item.getDescription();   
     model.addRow(new Object[]{name,description});
} 

Upvotes: 2

D&#225;vid Szab&#243;
D&#225;vid Szab&#243;

Reputation: 2247

Use a variable to store the next element.

 Drank next = it.next();
 String name = next.getName();
 String description = next.getDescription(); 

Upvotes: 4

Related Questions