KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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?
Tags (comma-separated)
Save Edits
Cancel