从类的数组中找出某个元素。vivizhyy 搞了件很 囧 的事情,导致代码写的很 cuo……事件Ⅱ:
这个其实可以用 map 做,设置 key. 但是懒得去搞那个东东,就用循环吧。循环完了之后,vivizhyy 忘记设置空的返回值,导致编译老出错,自己还郁闷半天~囧
那个函数应该是这样写的:
public static Employee getEmployee(Employee[] array, int id) {
int len = array.length;
if (len == 0) {
return null;
}
int i = 0;
for (; i < len; i++) {
if (array[i].getId() == id) {
return array[i];
}
}
return null;
}
我竟然在 iterator.remove() 里面传了参数!-_-|||然后竟然在这个很猪的问题上卡了一天……
以后遇见问题的时候先查 api……Iterators
The
ArrayList
methoditerator
returns ajava.util.Iterator<E>
object over the elements of the collection. An iterator is an object for traversing a collection from start to finish. In addition, using iterators you can safely removing elements from the collection during the traversal.The class
java.util.Iterator<E>
provides the following methods:
boolean hasNext()
. Returnstrue
if the iteration has more elements.
E next()
. Returns the next element in the iteration.
void remove()
. Removes from the collection the last element returned by the iterator. This method throws the exceptionIllegalStateException
, if the methodnext
has not been called, or the methodremove
has already been called after the last call to the methodnext
.For example, the following code concatenates the strings in a collection and then displays the result:
"ArrayList and Iterators"
.