1 Enumeration
public interface Enumeration<E> {
boolean hasMoreElements();
E nextElement();
}
An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
Hashtable.class
public synchronized Enumeration<K> keys() {
return this.<K>getEnumeration(KEYS);
}
public synchronized Enumeration<V> elements() {
return this.<V>getEnumeration(VALUES);
}
2 Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Method names have been improved.
3 建议
在所有输出操作中,以 Iterator 接口为最标准的输出操作,这一点始终要记住。在部分旧的操作中Enumeration 依然存在。现在普遍都使用Iterator来遍历集合类,只有特别明确声明必须使用Enumeration的才会用该类遍历集合。
Enumeration接口是JDK1.0时推出的,是最好的迭代输出接口,最早使用Vector(现在推荐使用ArrayList)时就是使用Enumeration接口进行输出。虽然Enumeration是一个旧的类,但是在JDK1.5之后为Enumeration类进行了扩充,增加了泛型的操作应用。
Enumeration接口常用的方法有hasMoreElements()(判断是否有下一个值)和 nextElement()(取出当前元素),这些方法的功能跟Iterator类似,只是Iterator中存在删除数据的方法,而此接口不存在删除操作。
Enumeration和Iterator接口功能相似,而且Iterator的功能还比Enumeration多,那么为什么还要使用Enumeration?这是因为java的发展经历了很长时间,一些比较古老的系统或者类库中的方法还在使用Enumeration接口,因此为了兼容,还是需要使用Enumeration。
这里提到了ArrayList和Vector,我们也补充一下两者的区别:3 代码实现
package pkgOne;
import java.util.Enumeration;
import java.util.Iterator;
public class Student {
private int[] scores=new int[100];
private int size=0;
public void addScore(int score) {
scores[size++]=score;
}
public Enumeration<Integer> getEnumeration() {
return new Enumeration<Integer>() {
private int count=0;
@Override
public boolean hasMoreElements() {
// TODO Auto-generated method stub
return (count<size);
}
@Override
public Integer nextElement() {
// TODO Auto-generated method stub
return scores[count++];
}
};
}
//真正完善的用法真参照ArrayList的iterator()方法,
//我在这里只是简单的实现基本功能,至于Iterator基本的规则,我们先不管。
public Iterator<Integer> getIterator() {
return new Iterator<Integer>() {
private int current=0;
private int pre=-1;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current<size;
}
@Override
public Integer next() {
// TODO Auto-generated method stub
pre++;
return scores[current++];
}
@Override
public void remove() {
// TODO Auto-generated method stub
//for循环赋值操作,更改pre和current下标
}
};
}
}