I have this code, but instead of implementing class enumeration I want to create an anonymous class in the method getEnumeration that does the job right in the return, hwo do I do that?

// File: TestList.java (Module 10)
//
// Author: Rahul Simha
// Created: Nov 2, 1998
//
// Starting point for Ex. 10.1: an anonymous class
// implementation of an Enumeration.
// The current file has the list implement the enumeration.

import java.util.*;

abstract class ComparableObject {
  public abstract String toString ();
  public abstract int compare (ComparableObject c);
}

class ListItem {

  ComparableObject data = null; 
  ListItem next = null;

  // Constructor.
  public ListItem (ComparableObject obj)
  {
    data = obj;  next = null;
  }
  
  // Accessor.
  public ComparableObject getData () 
  {
    return data;
  }
}


// LinkedList now implements Enumeration itself.

class LinkedList implements Enumeration {

  ListItem front = null;
  ListItem rear = null;
  int numItems = 0;      // Current number of items.

  // Instance method to add a data item.
  public void addData (ComparableObject obj)
  {
    if (front == null) {
      front = new ListItem (obj);
      rear = front;
    }
    else {
      // Find the right place.
      ListItem tempPtr=front, prevPtr=front;
      boolean found = false;
      while ( (!found) && (tempPtr != null) ) {
        if (tempPtr.data.compare(obj) > 0) {
          found = true;
          break;
	}
        prevPtr = tempPtr;
        tempPtr = tempPtr.next;
      }
      // Now insert.
      if (!found) { // Insert at rear.
	rear.next = new ListItem (obj);
	rear = rear.next;
      }
      else if (tempPtr == front) { // Insert in front.
	ListItem Lptr = new ListItem (obj);
        Lptr.next = front;
        front = Lptr;
      }
      else { // Insert in the middle.
	ListItem Lptr = new ListItem (obj);
	prevPtr.next = Lptr;
	Lptr.next = tempPtr;
      }
    }
    numItems++;
  }

  public void printList ()
  {
    ListItem listPtr = front;
    System.out.println ("List: (" + numItems + " items)");
    int i = 1;
    while (listPtr != null) {
      System.out.println ("Item# " + i + ": " 
                          + listPtr.getData());
                          // Must implement toString()
      i++;
      listPtr = listPtr.next;
    }
  }

  ListItem enumPtr;

  // Must implement this method.
  public boolean hasMoreElements ()
  {
    if (enumPtr == null)
      return false;
    else 
      return true;
  }

  // Must implement this method.
  public Object nextElement() 
  {
    Object obj = enumPtr.data;
    enumPtr = enumPtr.next;
    return obj;
  }

  // This is needed to return an Enumeration
  // instance to the user.
  public Enumeration getEnumeration ()
  {
    enumPtr = front;
    return this;      // Using the "this" reserved word.
  }

} // End of class "LinkedList"


// An object to use in the list:

class Person extends ComparableObject {

  String name;
  String ssn;

  // Constructor.
  public Person (String nameIn, String ssnIn)
  {
    name = nameIn;  ssn = ssnIn;
  }

  // Override toString()
  public String toString ()
  {
    return "Person: name=" + name + ", ssn=" + ssn;
  }

  // Must implement compare
  public int compare (ComparableObject obj)
  {
    Person p = (Person) obj;
    return name.compareTo (p.name);
  }

} // End of class "Person"


// Test class.

public class TestList {

  public static void main (String[] argv)
  {
    // Create a new list object.
    LinkedList L = new LinkedList ();

    // Create a Person instance and add it to list.
    L.addData (new Person ("Terminator", "444-43-4343"));
    L.addData (new Person ("James Bond", "666-65-6565"));
    L.addData (new Person ("Rambo", "555-54-5454"));
    L.addData (new Person ("Bruce Lee", "777-76-7676"));

    // Print contents via an Enumeration.
    Enumeration e = L.getEnumeration();
    while (e.hasMoreElements())
    {
      Person p = (Person) e.nextElement();
      System.out.println (p);
    }

  }

} // End of class "TestList"

Dani AI

Generated

was right to point toward an anonymous implementation. Returning a fresh anonymous Enumeration from getEnumeration keeps iteration state out of the list object, so you can create multiple independent enumerations at once and avoid clobbering a single cursor kept on the list instance. That also makes the list class simpler and safer to reuse.

A compact, working pattern is to capture the starting node in a final local and let the anonymous class keep its own cursor. This avoids storing iteration state in the list and keeps each Enumeration independent:

public Enumeration<ComparableObject> getEnumeration() {
  final ListItem start = front;
  return new Enumeration<ComparableObject>() {
    private ListItem cursor = start;

    public boolean hasMoreElements() {
      return cursor != null;
    }

    public ComparableObject nextElement() {
      if (cursor == null) throw new java.util.NoSuchElementException();
      ComparableObject out = cursor.getData();
      cursor = cursor.next;
      return out;
    }
  };
}

A few practical notes that close gaps in the thread: prefer generics if you use Java 5+ (as shown), and throw NoSuchElementException from nextElement() when there are no more items. For real-world code, consider implementing Iterator/Iterable instead so the list works with for-each and modern APIs. If you need robust detection of concurrent modification, maintain a modCount in the list, capture it in the iterator/enumeration as expectedModCount, and throw ConcurrentModificationException if it changes. If concurrent structural changes must be allowed, return a safe snapshot copy or use a concurrent collection instead.

This approach addresses the original problem without making the list object itself act as the enumeration and keeps the solution compatible with later Java best practices (generics, Iterator/Iterable).

Recommended Answers

All 2 Replies

Just like any anonymous implemenation

return new Enumeration() {

            public boolean hasMoreElements() {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public Object nextElement() {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };

Creating a small private inner class for the enumeration and returning an instance of that would be better though. You can see that idiom used quite a lot in the JDK classes.

Also keep in mind that Iterator is generally preferred to Enumeration these days.

Thanks! Solved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.