Iterate through string array in Java
I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first component and the component next to that one. So the first time I would get the component number one and the component number 2, the second time would get the number 2 and 3, the third time number 3 and 4... And so on until you get to the last component.
This how far I have come:
String[] elements = { "a", "a","a","a" };
for( int i = 0; i <= elements.length - 1; i++)
{
// get element number 0 and 1 and put it in a variable,
// and the next time get element 1 and 2 and put this in another variable.
}
How can I accomplish this?
Solution 1:
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
Solution 2:
String[] elements = { "a", "a", "a", "a" };
for( int i = 0; i < elements.length - 1; i++)
{
String element = elements[i];
String nextElement = elements[i+1];
}
Note that in this case, elements.length
is 4, so you want to iterate from [0,2]
to get elements 0,1
, 1,2
and 2,3
.
Solution 3:
String current = elements[i];
if (i != elements.length - 1) {
String next = elements[i+1];
}
This makes sure you don't get an ArrayIndexOutOfBoundsException
for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1
. It depends on your requirements.
Solution 4:
String[] elements = { "a", "a","a","a" };
for( int i=0; i<elements.length-1; i++)
{
String s1 = elements[i];
String s2 = elements[i+1];
}
Solution 5:
I would argue instead of testing i
less than elements.length - 1
testing i + 1
less than elements.length
. You aren't changing the domain of the array that you are looking at (i.e. ignoring the last element), but rather changing the greatest element you are looking at in each iteration.
String[] elements = { "a", "a","a","a" };
for(int i = 0; i + 1 < elements.length; i++) {
String first = elements[i];
String second = elements[i+1];
//do something with the two strings
}