HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sets, Check and add

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andsetscheckadd

Problem

Ok I have a method:

//_seen is defined as a HashSet earlier
public boolean isTerminal(Node node)
{
    if (_seen.contains(node.getState()))
    {
        return true;
    }
    else
    {
        _seen.add(node.getState());
        return false;
    }
}


What is the nicest way of doing this? It could use a variable to hold _seen.contains, and return just that, and maybe always add. Or, perhaps I could do:

public boolean isTerminal(Node node)
{
    return !_seen.add(node.getState());
}


but is that clear?

Solution

You could also use a variable to make the compact version more readable:

public boolean isTerminal(Node node)
{
    boolean stateWasAdded = _seen.add(node.getState());
    return !stateWasAdded;
}

Code Snippets

public boolean isTerminal(Node node)
{
    boolean stateWasAdded = _seen.add(node.getState());
    return !stateWasAdded;
}

Context

StackExchange Code Review Q#10182, answer score: 8

Revisions (0)

No revisions yet.