This type of loop is known as foreach
and as can be seen in this @bigown response , it was made to traverse a sequence of data from beginning to end. It is usually used to move through a list, where the index is not so important to what needs to be done in iterations (such as just displaying items in sequence).
As an alternative to the problem presented, you can use traditional for
, starting the index from 1 to the end, so you can compare in a more "elegant" way by comparing the current item with the previous one. Here's an example:
String[] array = {"a","b","c","d"};
for(int i = 1; i < array.length; i++){
System.out.print("Valor anterior: " + array[i-1]);
System.out.print(" - ");
System.out.println("Valor atual: " + array[i]);
}
Output:
Previous value: a - Current value: b
Previous value: b - Current value: c
Previous value: c - Current value: d
See working at IDEONE .
Adapting to your code would look like this:
for(int i = 1; i < PilhaTokens.size(); i++){
if(listaReserva.contains(PilhaToken.get(i)) &&
listaOperadores.contains(PilhaToken.get(i-1))){
System.out.println("Variavel com nome de Palavra Reservada");
}
}