0

Is there a way to immediately return a boolean when a condition is met during a for loop that is scanning through a list?

I've been using this "flag" method when doing these kinds of things.

The class referred to by this is an object that is made up of multiple Point objects.

This method returns true if any one of the Point objects in its pointsCovered ArrayList is equal to the Point p passed into the method (if the object contains the input point, hence the method name).

boolean containsPoint(Point p) {

    boolean flag = false;

    for (int i = 0; i < this.length; i++)
    {
        if (pointsCovered.get(i).equals(p)) {
            flag = true;
            break;
        }
    }

    return flag;
}

I can't find anything similar to this by searching.

Basically I'm asking if there's a better or standard way of doing this.

Edit: For clarification, I was using this flag variable because I didn't know that returning a statement in a for loop would terminate the loop and immediate return the value.

Cheers.

Josh
  • 69
  • 11
  • 2
    Why not simply `return true;` inside your `if`? – QBrute Apr 30 '18 at 07:27
  • Have a look at [return in for loop or outside loop](https://stackoverflow.com/questions/10800195/return-in-for-loop-or-outside-loop) or [Does returning a value break a loop?](https://stackoverflow.com/questions/10661081/java-does-returning-a-value-break-a-loop) or [return statement within the for loop](https://stackoverflow.com/questions/30880348/java-return-statement-within-the-for-loop) – Malte Hartwig Apr 30 '18 at 07:35

2 Answers2

4

Drop the flag completely and return asap:

boolean containsPoint(Point p) {

    for (int i = 0; i < this.length; i++)
    {
        if (pointsCovered.get(i).equals(p)) {
            return true;
        }
    }

    return false;
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • So a return statement will immediately terminate the method no matter where it occurs? – Josh Apr 30 '18 at 07:30
  • 1
    @Josh in almost all cases: yes. *If* you `return` from within a `try` block with a `finally` block that block will still be executed but that should not concern you here. – luk2302 Apr 30 '18 at 07:31
  • 1
    @Josh "no matter where it occurs" it won't terminate the method if the return is inside a lambda or a method in a locally-defined class. – Andy Turner Apr 30 '18 at 07:31
4

If you want to check the entire collection, you can do this in one line:

boolean containsPoint(Point p) {
    return pointsCovered.contains(p);
}
  • +1, but this is a) assuming it is a `Collection` (it looks like it is); b) `pointsCovered.size() == this.length`; c) various other subtle assumptions about the implementations of the classes. – Andy Turner Apr 30 '18 at 07:38
  • Wow, that's useful. I'm only two semesters into coding so there's a lot of useful methods I haven't learned yet. – Josh Apr 30 '18 at 07:42