As part of an exercise, am implementing an ArrayList which will support Enumerations.
Following is the adapter that converts an Iterator to an Enumeration:
public class MyEnumeratorAdapter<Object> implements Enumeration<Object> {
private Iterator<Object> adaptee;
public MyEnumeratorAdapter(Iterator<Object> it) {
this.adaptee = it;
}
@Override
public boolean hasMoreElements() {
return adaptee.hasNext();
}
@Override
public Object nextElement() {
return adaptee.next();
}
}
and my arraylist class is:
public class MyArrayList<Object> extends ArrayList<Object> {
public MyArrayList() {
this.enumerator = new MyEnumeratorAdapter<Object>(this.iterator());
}
public Enumeration<Object> enumerator() {
return this.enumerator;
}
public boolean hasMoreElements() {
return this.enumerator.hasMoreElements();
}
public Object nextElement() {
return this.enumerator.nextElement();
}
private static final long serialVersionUID = 1L;
private Enumeration<Object> enumerator;
}
however, when I try this testing with the following code, I'm getting java.util.ConcurrentModificationException
public static void main(String[] args) {
MyArrayList<String> names = new MyArrayList<String>();
names.add("jim");
names.add("jack");
names.add("jai");
for (Enumeration<String> iterator = names.enumerator(); iterator
.hasMoreElements();) {
String name = (String) iterator.nextElement();
System.out.println(name);
}
}
what mistake am I doing?
Can I have an ArrayList class that support Enumerations?
MyArrayList
has several issues:
Iterator
on a zero sized array list; you must create a fresh iterator each time you call enumerator MyArrayList
This class should fix these issues:
public class MyArrayList<T> extends ArrayList<T> {
public Enumeration<T> enumerator() {
return new MyEnumeratorAdapter(this.iterator());
}
}
You end up using the same Iterator
repeatedly. You need a new one each time (by creating a new Enumeration
each time).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.