gpt4 book ai didi

java - 多个 else if block 或继续?

转载 作者:搜寻专家 更新时间:2023-11-01 02:24:32 25 4
gpt4 key购买 nike

<分区>

在解决一个不需要动脑的任务时,我想到了一个问题:

/**
* 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 { //found element
return node.getElement();
}
}
return null;
}

while block 中,只有一个if语句可以为真。所以 while block 可以使用 continue 而不是 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;
}
//found element
return node.getElement();
}

这两种方法在性能上有什么区别吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com