001    /*
002     * LAPIS lightweight structured text processing system
003     *
004     * Copyright (C) 1998-2002 Carnegie Mellon University,
005     * Copyright (C) 2003 Massachusetts Institute of Technology.
006     * All rights reserved.
007     *
008     * This library is free software; you can redistribute it
009     * and/or modify it under the terms of the GNU General
010     * Public License as published by the Free Software
011     * Foundation, version 2.
012     *
013     * LAPIS homepage: http://graphics.lcs.mit.edu/lapis/
014     */
015    
016    
017    package lapisx.enum;
018    import java.util.Enumeration;
019    import java.util.NoSuchElementException;
020    import java.util.Vector;
021    /**
022     * Enumeration which can be restarted from the beginning.
023     */
024    public class MemoizedEnumeration implements RestartableEnumeration  {
025        Vector v;  // elements which have already been returned 
026        Enumeration e1; // enumeration of v
027        Enumeration e2; // main enumeration 
028    
029        public MemoizedEnumeration (Enumeration e) {
030            this.v = new Vector ();
031            this.e2 = e;
032        }
033    
034        public MemoizedEnumeration (Vector v) {
035            this.v = (Vector) v.clone ();
036            this.e1 = this.v.elements ();
037        }
038    
039        public boolean hasMoreElements () {
040            if (e1 != null) {
041                if (e1.hasMoreElements ())
042                    return true;
043                else
044                    e1 = null;
045            }
046    
047            if (e2 != null) {
048                if (e2.hasMoreElements ())
049                    return true;
050                else
051                    e2 = null;
052            } 
053    
054            return false;
055        }
056    
057        public Object nextElement () {
058            if (e1 != null)
059                try {
060                    return e1.nextElement ();
061                } catch (NoSuchElementException e) {
062                    e1 = null;
063                }
064    
065            if (e2 != null)
066                try {
067                    Object o = e2.nextElement ();
068                    v.addElement (o);
069                    return o;
070                } catch (NoSuchElementException e) {
071                    e2 = null;
072                }
073    
074            throw new NoSuchElementException ();
075        }
076    
077        public void restart () {
078            e1 = v.elements ();
079        }
080    }