mercredi 4 février 2015

multiple else if blocks or continue?

While solving a mindless task, a question came to my mind:



/**
* Find element by key in binary tree.
*/
public E find(K key) {
BinaryTreeNode<K, E> node = this.root;
while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
} else if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
} else if (node.getKey().compareTo(key) == 0) { //found element
return node.getElement();
}
}
return null;
}


In the while block, only one if statement can be true. So the while block could be written using continue instead of else if:



while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
continue;
}
if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
continue;
}
if (node.getKey().compareTo(key) == 0) { //found element
return node.getElement();
}
}


Is there any difference between the two methods? Which one is preferable?


Aucun commentaire:

Enregistrer un commentaire