views:

165

answers:

2

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?

+1  A: 

You end up using the same Iterator repeatedly. You need a new one each time (by creating a new Enumeration each time).

Tom Hawtin - tackline
+1  A: 

MyArrayList has several issues:

  1. it creates an Iterator on a zero sized array list; you must create a fresh iterator each time you call enumerator
  2. it implements method of Enumerable directly in MyArrayList
  3. it doesn't use generics properly

This class should fix these issues:

public class MyArrayList<T> extends ArrayList<T> {

    public Enumeration<T> enumerator() {
        return new MyEnumeratorAdapter(this.iterator());
    }
}
dfa
Fixed 1 and 3 issues. Thank You.Where should I place the methods of Enumeration if myArrayList has to support it?
HanuAthena
in MyEnumeratorAdapter?
dfa