Today, someone attended me to bad use of the return
keyword in Java. I had written a simple for
loop to validate that something is in an array. Supposing array
is an array of length n
, this was my code:
for (int i = 0; i < array.length; ++i) {
if (array[i] == valueToFind) {
return true;
}
}
return false;
Now someone told me that this is not very good programming because I use the return
statement inside a loop and this would cause garbage collection to malfunction. Therefore, better code would be:
int i = 0;
while (i < array.length && array[i] != valueToFind) {
++i;
}
return i != array.length;
The problem is that I can't come up with a proper explenation of why the first for loop isn't a good practice. Can somebody give me an explanation?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…