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 */ 013package org.jikesrvm.compilers.opt.util; 014 015import java.util.Enumeration; 016import 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 */ 022public 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 @Override 045 public T nextElement() { 046 if (done) { 047 throw new NoSuchElementException(); 048 } 049 S o = next; 050 advance(); 051 return f.map(o); 052 } 053 054 @Override 055 public boolean hasMoreElements() { 056 return !done; 057 } 058 059 public static class Filter<S, T> { // override with your mapping. 060 061 public boolean isElement(S o) { 062 return true; 063 } 064 065 @SuppressWarnings("unchecked") 066 public T map(S o) { 067 return (T) o; 068 } 069 } 070}