In the book 'Data structures and algorithms in java' the following Array search method code is provided:
{
int j;
for(j=0; j< nElems; j++) // for each element,
if( a[j].getLast().equals(searchName)) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return a[j]; // no, found it
}
I am trying to understand why there needs to be a if(j == nElems) check? Wouldn't the method work the same if it were written as:
{
int j;
for(j=0; j <nElems; j++)
if( a[j].getLast().equals(searchName))
return a[j];
return null;
}