I have two methods to iterate through a hash map containing a key(String) and a value(Arraylist) and add all the values from the Arraylists to a single Arraylist.
Method one did not work so I created Method two which fixed the issue but i'm not sure why method one did not work. Could someone please explain why method two works and method one does not?
Method 1
public ArrayList<Person> getPeopleList()
{
Iterator<ArrayList<Person>> iter = people.values().iterator();
ArrayList<Person> allPersons = new ArrayList<>();
while (iter.hasNext())
{
for (int i = 0; i < iter.next().size(); i++)
{
allPersons.add(iter.next().get(i));
}
}
return allPersons;
}
Method 2
public ArrayList<Person> getPeopleList()
{
Iterator<ArrayList<Person>> iter = people.values().iterator();
ArrayList<Person> allPersons = new ArrayList<>();
ArrayList<Person> persons;
while (iter.hasNext())
{
persons = iter.next();
for (Person p : persons)
{
allPersons.add(p);
}
}
return allPersons;
}
next()twice per inner iteration, when it shouldn't be callingiter.next()at all - you want a single call toiter.next()per outer iteration.allPersons?