001/*
002 * HA-JDBC: High-Availability JDBC
003 * Copyright (C) 2012  Paul Ferraro
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Lesser General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package net.sf.hajdbc.util;
019
020import java.util.Iterator;
021import java.util.List;
022import java.util.ListIterator;
023
024/**
025 * An iterable facade for a list whose iterator operates in reverse order.
026 * @author Paul Ferraro
027 */
028public class Reversed<T> implements Iterable<T>
029{
030        private final List<T> list;
031
032        public Reversed(List<T> list)
033        {
034                this.list = list;
035        }
036
037        /**
038         * {@inheritDoc}
039         * @see java.lang.Iterable#iterator()
040         */
041        @Override
042        public Iterator<T> iterator()
043        {
044                final ListIterator<T> iterator = this.list.listIterator(this.list.size());
045                
046                return new Iterator<T>()
047                {
048                        @Override
049                        public boolean hasNext()
050                        {
051                                return iterator.hasPrevious();
052                        }
053                        
054                        @Override
055                        public T next()
056                        {
057                                return iterator.previous();
058                        }
059                        
060                        @Override
061                        public void remove()
062                        {
063                                iterator.remove();
064                        }
065                };
066        }
067}