001/*******************************************************************************
002 * This software is provided as a supplement to the authors' textbooks on digital
003 *  image processing published by Springer-Verlag in various languages and editions.
004 * Permission to use and distribute this software is granted under the BSD 2-Clause 
005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 
006 * Copyright (c) 2006-2016 Wilhelm Burger, Mark J. Burge. All rights reserved. 
007 * Visit http://imagingbook.com for additional details.
008 *******************************************************************************/
009
010package imagingbook.lib.util;
011
012import java.util.Iterator;
013
014//import java.util.Iterator;
015
016/**
017 * This class implements a 1D map for arbitrary objects
018 * with flexible bottom and top index,
019 * similar to an array in Pascal. Containers are immutable.
020 */
021public class LinearContainer<T> implements Iterable<T> {
022        
023        private final int botIndex, topIndex;
024        private final T[] data;
025        
026        /**
027         * Creates a LinearContainer with the index range
028         * [0, n - 1], like an ordinary array.
029         * @param n size of the container.
030         */
031        public LinearContainer(int n) {
032                this(0, n - 1);
033        }
034        
035        /**
036         * Creates a LinearContainer with the index range
037         * [botIndex, topIndex].
038         * @param botIndex bottom (smallest) index.
039         * @param topIndex top (largest) index.
040         */
041        @SuppressWarnings("unchecked")
042        public LinearContainer(int botIndex, int topIndex) {
043                if (botIndex > topIndex) {
044                        throw new IllegalArgumentException("LinearContainer: botIndex > topIndex");
045                }
046                this.botIndex = botIndex;
047                this.topIndex = topIndex;
048                int n = topIndex - botIndex + 1;
049                data = (T[]) new Object[n];
050        }
051        
052        public T getElement(int k) {
053                return data[k - botIndex];
054        }
055        
056        public void setElement(int k, T elem) {
057                // TODO: check for out-of-bounds index k
058                data[k - botIndex] = elem;
059        }
060
061        public int getBotIndex() {
062                return botIndex;
063        }
064        
065        public int getTopIndex() {
066                return topIndex;
067        }
068
069        public Iterator<T> iterator() {
070                return new ArrayIterator<T>(data);
071        }
072
073}