Takichiii Takichiii - 2 months ago 6
Java Question

Return an element within a for-each outside it in Java

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

Answer

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;
}
Comments