vendredi 20 février 2015

Java: Style issue for if statement returns?

Say that I had a method that required me to loop through a data structure, then return a number stored in a particular index if it was equal to a given number. If two numbers in the data structure were equal, then it would return the number that came first.



public static int method(int value, List<Integer> list){
for (Integer i: list){
if (i == value){
return i;
}
}
}


This is a problematic solution, because the method may not necessarily return. I suppose you could create a variable to store a reference to the equivalent value and return that, so the compiler does not issue a error about the lack of a return statement, but that would be pointless code.


Is there a better way to do this? Would you just return 0, or return null, in the case that you are returning an object?


Aucun commentaire:

Enregistrer un commentaire