<分区>
我必须编写一个函数来从链表中删除一个元素(我的,而不是 Collections 框架的),所以这是我的第一次尝试:
public void remove(E element) {
Cell<E> cell = sentinel;
int i = 0;
while (i < count) {
if (cell.getElement().equals(element)) {
cell.getPrevious().setNext(cell.getNext());
--count;
return;
}
++i;
cell = cell.getNext();
}
}
我的问题是:这样使用 return
好吗?
更一般地说,当检查条件并且运行以下指令没有意义时,使用 return
对我来说是有意义的:
void func() {
while (condition) {
if (something) {
instructions;
return;
}
more instructions;
}
}
但是由于它的可读性不是很好,而且每个人都说在 java 中可读性是优先考虑的,所以我不得不考虑另一种方法。所以我改变了条件并使用了一个额外的 boolean 值。
public void remove(E element) {
boolean found = false;
Cell<E> cell = sentinel;
int i = 0;
while (!found && i < count) {
if (cell.getElement().equals(element))
found = true;
else {
++i;
cell = cell.getNext();
}
}
if (found) {
cell.getPrevious().setNext(cell.getNext());
--count;
}
}
这样一来,就没有奇怪的return
了,指令只在必须执行时才执行。如果我再次遇到这种情况,我想我将不得不像这样重写循环。
也许我完全错了,第一种方法更好。你怎么看?