Reputation: 563
I would like to return an element of a List
that I loop through with a for-each loop , outside the loop.
Here is my method :
private List<Taxi> taxis = new ArrayList<Taxi>();
Taxi scheduleTaxi(){
for (Taxi taxi : taxis){
if (taxi.isFree()) {
return taxi;
}
}
return null; //I would like it to return taxi not null
}
Any suggestions? Thanks
Upvotes: 1
Views: 69
Reputation: 2540
If I understand the question correctly, you aren't asking how to return from inside an iterative loop, but are trying to avoid returning null
if no suitable match is found, correct...? It makes sense, I suppose; I've had some colleagues who were opposed to working with null for whatever reason.
One approach you can take is the "sentinel value" approach, as one of my mentors once called it (might be there's a better name for it). Basically, you have one specific Taxi
instance that represents the absence of a Taxi entirely. In your Taxi class...
public class Taxi {
public static final Taxi NO_TAXI = new Taxi(/*constructor params here*/);
// Insert the rest of your class here!
}
Basically, you want to initialize a globally-accessible, constant Taxi instance that represents the concept of not being a Taxi. Users of your class can look to that instance and know "Oh, this means that there was no Taxi."
So, your original scheduleTaxi
method would look something like this:
private List<Taxi> taxis = new ArrayList<Taxi>();
Taxi scheduleTaxi(){
for (Taxi taxi : taxis){
if (taxi.isFree()) {
return taxi;
}
}
// No free taxi found! Return the no-taxi instance.
return Taxi.NO_TAXI;
}
Make sure you include that the method will return NO_TAXI if no free taxi is found, so that your users won't be confused!
I personally prefer to just work with null
. :)
Upvotes: 1
Reputation: 498
What you've wrote is exactly right (you could be getting null because there aren't any that's free I guess) but here's another simple way of doing it to help you understand the concept.
Assign the Taxi
that's isFree()
to a reference and return that outside the for-loop like this,
private List<Taxi> taxis = new ArrayList<Taxi>();
Taxi freeTaxi = null;
Taxi scheduleTaxi(){
for (Taxi taxi : taxis){
if (taxi.isFree()) {
freeTaxi = taxi;
break; //since you already found what you want, no need to keep going.
}
}
return freeTaxi;
}
Upvotes: 1
Reputation: 48258
It looks ok, if the question is related to "should I return a null reference??", then its OK.
if you change a little the name of the method and add a good java doc, like>
public Taxi getAvaliableTaxi(){
for (Taxi taxi : taxis){
if (taxi.isFree()) {
return taxi;
}
}
return null; //I would like it to return taxi not null
}
then I can see that it could be possible that no taxis are avaliable or free by the time I call the method.. so null is defenitely a valid return type Is my responsability as client of your API to check the return before I jump in a null-Taxi...
Upvotes: 0