dhssa dhssa - 1 year ago 85
Java Question

How do I access the next element in for each loop in Java?

I am using a for each loop to visit each element of an array of Strings and checking specific characteristics of those Strings. I need to access the next element in this loop if the current one has shown the character desired. So the current on is just an indicator for me that the next one is the one I need to grep and process. Is there any way to store the current one and process the right next one?


Answer Source

You either need to use an indexed loop.

for(int i=0;i<strings.length-1;i++) {
    String curr = strings[i];
    String next = strings[i+1];

or you need to compare the current to the previous not the next.

String curr = null;
for(String next: strings) {
    if (curr != null) {
        // compare
    curr = next;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download