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.ArrayList;
016import java.util.Enumeration;
017import java.util.NoSuchElementException;
018
019/**
020 * An enumerator that provides access to the reverse order of elements for
021 * a given {@link Enumeration}.
022 */
023public final class ReverseEnumerator<T> implements Enumeration<T> {
024
025  private final ArrayList<T> vec;
026  private int index;
027
028  public ReverseEnumerator(Enumeration<T> e) {
029    vec = new ArrayList<T>();
030    while (e.hasMoreElements()) {
031      vec.add(e.nextElement());
032    }
033    index = vec.size();
034  }
035
036  @Override
037  public boolean hasMoreElements() {
038    return index > 0;
039  }
040
041  @Override
042  public T nextElement() {
043    index--;
044    if (index >= 0) {
045      return vec.get(index);
046    } else {
047      throw new NoSuchElementException();
048    }
049  }
050
051}