001    /*
002     *  This file is part of the Jikes RVM project (http://jikesrvm.org).
003     *
004     *  This file is licensed to You under the Eclipse Public License (EPL);
005     *  You may not use this file except in compliance with the License. You
006     *  may obtain a copy of the License at
007     *
008     *      http://www.opensource.org/licenses/eclipse-1.0.php
009     *
010     *  See the COPYRIGHT.txt file distributed with this work for information
011     *  regarding copyright ownership.
012     */
013    package org.jikesrvm.compilers.opt.util;
014    
015    import java.util.Enumeration;
016    import java.util.NoSuchElementException;
017    
018    /**
019     * A <code>FilterEnumerator</code> filters and maps a source
020     * <code>Enumeration</code> to generate a new one.
021     */
022    public class FilterEnumerator<S, T> implements Enumeration<T> {
023      final Enumeration<S> e;
024      final Filter<S, T> f;
025      private S next;
026      private boolean done;
027    
028      public FilterEnumerator(Enumeration<S> e, Filter<S, T> f) {
029        this.e = e;
030        this.f = f;
031        advance();
032      }
033    
034      private void advance() {
035        while (e.hasMoreElements()) {
036          next = e.nextElement();
037          if (f.isElement(next)) {
038            return;
039          }
040        }
041        done = true;
042      }
043    
044      public T nextElement() {
045        if (done) {
046          throw new NoSuchElementException();
047        }
048        S o = next;
049        advance();
050        return f.map(o);
051      }
052    
053      public boolean hasMoreElements() {
054        return !done;
055      }
056    
057      public static class Filter<S, T> {                  // override with your mapping.
058    
059        public boolean isElement(S o) {
060          return true;
061        }
062    
063        @SuppressWarnings("unchecked")
064        public T map(S o) {
065          return (T) o;
066        }
067      }
068    }