0

I have a List that contains many rows of data.What i want to do is return only the first iterated value and nothing else.

public int getnumber() {    
    for (Bike temp : bikes) {
        return temp.getBikeID();
        break;
    }
}

I tried something like the above..but the break statement is unreachable. How may i achieve this ?

I know that i could still just declare a variable outside of the loop then assign the value in the loop but the returned value will be the last row.

4
  • 3
    Why don't you simply do (after checking the size of the list and if the first element is not null)public int getnumber(){return bikes.get(0).getBikeId();}? Commented Apr 1, 2014 at 13:54
  • Thanks it's just my inexperience :p Commented Apr 1, 2014 at 13:55
  • you are doing a return before you break... then the execution is finished there. Commented Apr 1, 2014 at 13:55
  • What's being returned if there is no bike in bikes? Commented Apr 1, 2014 at 13:57

5 Answers 5

4

This is because of the return statement before break. The return statement will take the execution to the calling method. so, the break statement is unreachable.

You don't need to iterate to get the first value of the collection. The first index would be 0. so, just make it

if(bikes!=null && bikes.size() > 0)
return bikes.get(0).getBikeId();
return -1; // `-1` denotes failure or put anything relevant to failure
Sign up to request clarification or add additional context in comments.

1 Comment

@aliteralmind I have updated the code to handle failure situation. Thanks
3

Do not loop and try directly :

 return bikes.get(0).getBikeId();

1 Comment

Will fail if there is no first element, unlike the loop approach.
2

Try like this -

// null and size check to make sure if there is something on 0 index
return bikes != null && bikes.size > 0 ? bikes.get(0).getBikeId() : 0;

Comments

1

Simply delete the break statement. In fact, this is all you need:

for (Bike temp : bikes) return temp.getBikeID();
return -1;

In place of return -1 put the behavior you prefer for the "not found" case.

Comments

1

You can access you list's indices via .get() directly. No need for an iteration if you only need one or a hand full of specific elements:

public int getnumber() {
    int result = 0;

    if (bikes != null && bikes.size() > 0)
        result = bikes.get(0).getBikeID();

    return result;
}

Or even shorter, with the use of the ternary operator (condition ? true : false;):

public int getnumber() {
    return (bikes != null && bikes.size() > 0) ? bikes.get(0).getBikeId() : 0;
}

Comments