D
Daniel Pitts
Java 1.5 finaly gave us an elegant for each construct, but for-each
lacks the ability to manipulate the underlying Iterable structure.
Generally, the way to do this is (in pseudo-code
Obtain the iterator.
L: Check if it has a next element
get the next element
process the element.
repeat from L
This can be coded in Java a few ways.
// For method:
for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
{
E e = iterator.next();
if (shouldRemove(e)) {
iterator.remove(e);
}
}
// vs
// While method:
Iterator<E> iterator = iterable.iterator();
while (iterator.hasNext()) {
E e = iterator.next();
if (shouldRemove(e)) {
iterator.remove(e);
}
}
Both approaches have their pros and cons, but I'm interested to see
what people think.
I'll post my opinion later.
lacks the ability to manipulate the underlying Iterable structure.
Generally, the way to do this is (in pseudo-code
Obtain the iterator.
L: Check if it has a next element
get the next element
process the element.
repeat from L
This can be coded in Java a few ways.
// For method:
for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
{
E e = iterator.next();
if (shouldRemove(e)) {
iterator.remove(e);
}
}
// vs
// While method:
Iterator<E> iterator = iterable.iterator();
while (iterator.hasNext()) {
E e = iterator.next();
if (shouldRemove(e)) {
iterator.remove(e);
}
}
Both approaches have their pros and cons, but I'm interested to see
what people think.
I'll post my opinion later.