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    package lapisx.sort;
017    import java.util.Enumeration;
018    //import java.util.NoSuchElementException;
019    import java.util.Vector;
020    
021    /**
022     * Enumeration which reorders the elements of another enumeration.
023     */
024    public abstract class SortedEnumeration implements Enumeration {
025        Enumeration original; // original enumeration
026        Enumeration sorted; // enumeration after sorting
027    
028        public SortedEnumeration (Enumeration e) {
029            original = e;
030        }
031    
032        public abstract int compare (Object o1, Object o2);
033    
034        public boolean hasMoreElements () {
035            if (sorted == null)
036                sorted = sort ();
037            return sorted.hasMoreElements ();
038        }
039    
040        public Object nextElement () {
041            if (sorted == null)
042                sorted = sort ();
043            return sorted.nextElement ();
044        }
045    
046        Enumeration sort () {
047            // read the original enumeration into a vector
048            Vector v = new Vector ();
049            while (original.hasMoreElements ())
050                v.addElement (original.nextElement ());
051    
052            // sort the vector
053            MergeSort.sort (new SortableVector (v) {
054                    public int compare (Object o1, Object o2) {
055                        return SortedEnumeration.this.compare (o1, o2);
056                    }
057                });
058    
059            // enumerate its elements
060            return v.elements ();
061        }
062    }