patternjavaMinor
Sets, Check and add
Viewed 0 times
andsetscheckadd
Problem
Ok I have a method:
What is the nicest way of doing this? It could use a variable to hold
but is that clear?
//_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.