我正在编写一个方法,如果链接列表中的元素,则返回TRUE;如果不在列表中,则返回FALSE。
我想知道是否有更简洁的方法来编码...
以下是我的代码的快速视图:
public boolean estElement(T item) {
boolean elmExist = false;
this.actual = this.head;
if (item != null && this.actual != null) {
T elmSearch;
while (this.actual != null && !elmExist) {
elmSearch = actual.getElement();
if (elmSearch.equals(item)) {
elmExist = true;
} else {
this.actual = this.actual.nextLink();
}
}
}
return elmExist;
}
答案 0 :(得分:1)
找到元素后立即存在循环和函数:
while (this.actual != null && !elmExist)
{
elmSearch = actual.getElement();
if (elmSearch.equals(item)) return true;
this.actual = this.actual.nextLink();
}
return false;
答案 1 :(得分:1)
你可以做得更短,就像在下面的代码片段中一样(我发现它比带有中断或返回的循环更漂亮):
public boolean estElement(T item) {
Node<T> current;
for (current = head ; current != null && current.value != item ; current = current.nextLink());
return current != null;
}
正如一句话,
if (myVar != null) { while (myVar != null) { ... } }
等同于
while (myVar != null) { ... }
所以你不需要两次写相同的条件。但是,如果else/else if
块中有if
条款或其他说明,则它将不再相同。