Oi pessoal,
Tenho uma duvida. Estava estudando coleções (List, Set, Queue, SorteSet, Deque, Map, etc…) e obviamente acabei lendo sobre Iterator. E na documentacao diz que o Iterator e a unica forma segura de remover um elemento durante uma iteracao;
Note that Iterator.remove
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
Logo tentei fazer um exemplo simples usando o iterator.
Na minha lista eu verifico 2 valores e removo o menor entre eles.
Um código clássico para fazer isso seria:
//classe Division
//(…) private List teams = new ArrayList<>();
//variavel divisionLest
//Division divisionLest = new Division(“xxxxxx”);
for (int i = 0; i < divisionLest.getTeams().size(); i++) {
int x = i+1;
Team t1 = divisionLest.getTeam(i);
Team t2 = divisionLest.getTeam(x);
if (t1.getScore() < t2.getScore()) {
//remove t1
divisionLest.getTeams().remove(i);
} else {
//remove t2
divisionLest.getTeams().remove(x);
}
}
Tentei fazer o mesmo usando Iterator, mas ele nao possui um “previous”.
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
Entao usei o listIterator, mas o listIterator nao possui o “elemento atual”.
A ListIterator
has no current element; its cursor position always lies between the element that would be returned by a call to previous()
and the element that would be returned
https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html
Entao a ideia basica do meu codigo seria
ListIterator<Team> listIterator = divisionLest.getTeams().listIterator();
while (listIterator.hasNext()) {
Team t1 = listIterator.atual(); //Metodo nao existe
Team t2 = listIterator.next();
System.out.println(listIterator.nextIndex());
if (t1.getScore() < t2.getScore()) {
//remove t1
} else {
//remove t2
}
}
Mas e obvio que isso nao funciona. Alguem tem alguma sugestao de como faze-lo?
Obrigado