Using Flags

Flagging is a simple programming concept, yet many developers learn it only in-the-field. Using simple examples, we try to introduce the important concept of flagging.

Simple Searching

Searching for a particular item within a collection is often performed, usually by traversing:


    String toFind = "cat";
    for (int i=0;i<list.size();i++) {
        if (toFind.equals(list.get(i))) {
            // Found
            break;
        }
    }

Flagging

But how to you check that a particular item is NOT inside a collection? For example, we onlt want to add an item to the collection IF the item to add is not already in the list. Sadly, the above method doesn’t work. We can only confirm an item is not within a collection after we have traversed the WHOLE collection, since it is possible that the item is the last item in the list. Therefore a boolean variable, commonly termed as a “flag”, is introduced.


    boolean inList = false;
    for (int i=0;i<list.size();i++) {
        if (toFind.equals(list.get(i))) {
            inList = true;
            break;
        }
    }
    if (!inList) {
        // Confirmed not in List
    }

The flag is checked at the end of the loop to see if the item was found. If we found the item in the middle we can break out of the loop since we’re sure that the item exists.

Counting

Flagging can be used to answer yes/no questions, whether something is not in a list. The idea can be extended by using integer flags to support counting. To count how many children are there in the collection,


    int childrenCount = 0;
    for (int i=0;i<list.size();i++) {
        Person person = (Person)list.get(i)
        if (child.getAge() < 12) {
            childrenCount++;
        }
    }

As usual we have to traverse till the END of the list to ensure all children are counted.

Additional Notes

Also look at implementing the equals() method for searching an item within a collection, and the Collections.contains() method. This concept is applicable to all languages that support looping (actually branching is enough to implement this concept, but in a different manner: see basic programming concepts)

RSS feed for comments on this post · TrackBack URL

Leave a Comment