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 comp
Those algorithms are both incorrect because of the comparison:
for( int i = 0; i < elements.length - 1; i++)
or
for(int i = 0; i + 1 < elements.length; i++) {
It's true that the array elements range from 0
to length - 1
, but the comparison in that case should be less than or equal to
.
Those should be:
for(int i = 0; i < elements.length; i++) {
or
for(int i = 0; i <= elements.length - 1; i++) {
or
for(int i = 0; i + 1 <= elements.length; i++) {
The array ["a", "b"]
would iterate as:
i = 0 is < 2: elements[0] yields "a"
i = 1 is < 2: elements[1] yields "b"
then exit the loop because 2 is not < 2.
The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.
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);
}
String[] elements = { "a", "a","a","a" };
for( int i=0; i<elements.length-1; i++)
{
String s1 = elements[i];
String s2 = elements[i+1];
}
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.