    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.collections4.list;
    018
    019import java.util.ArrayList;
    020import java.util.Collection;
    021import java.util.Collections;
    022import java.util.List;
    023
    024/**
    025 * Decorates another {@code List} to make it seamlessly grow when
    026 * indices larger than the list size are used on add and set,
    027 * avoiding most IndexOutOfBoundsExceptions.
    028 * <p>
    029 * This class avoids errors by growing when a set or add method would
    030 * normally throw an IndexOutOfBoundsException.
    031 * Note that IndexOutOfBoundsException IS returned for invalid negative indices.
    032 * </p>
    033 * <p>
    034 * Trying to set or add to an index larger than the size will cause the list
    035 * to grow (using {@code null} elements). Clearly, care must be taken
    036 * not to use excessively large indices, as the internal list will grow to
    037 * match.
    038 * </p>
    039 * <p>
    040 * Trying to use any method other than add or set with an invalid index will
    041 * call the underlying list and probably result in an IndexOutOfBoundsException.
    042 * </p>
    043 * <p>
    044 * Take care when using this list with {@code null} values, as
    045 * {@code null} is the value added when growing the list.
    046 * </p>
    047 * <p>
    048 * All sub-lists will access the underlying list directly, and will throw
    049 * IndexOutOfBoundsExceptions.
    050 * </p>
    051 * <p>
    052 * This class differs from {@link LazyList} because here growth occurs on
    053 * set and add, where {@code LazyList} grows on get. However, they
    054 * can be used together by decorating twice.
    055 * </p>
    056 *
    057 * @param <E> the type of the elements in the list.
    058 * @see LazyList
    059 * @since 3.2
    060 */
    061public class GrowthList<E> extends AbstractSerializableListDecorator<E> {
    062
    063    /** Serialization version */
    064    private static final long serialVersionUID = -3620001881672L;
    065
    066    /**
    067     * Factory method to create a growth list.
    068     *
    069     * @param <E> the type of the elements in the list
    070     * @param list  the list to decorate, must not be null
    071     * @return a new growth list
    072     * @throws NullPointerException if list is null
    073     * @since 4.0
    074     */
    075    public static <E> GrowthList<E> growthList(final List<E> list) {
    076        return new GrowthList<>(list);
    077    }
    078
    079    /**
    080     * Constructor that uses an ArrayList internally.
    081     */
    082    public GrowthList() {
    083        super(new ArrayList<>());
    084    }
    085
    086    /**
    087     * Constructor that uses an ArrayList internally.
    088     *
    089     * @param initialCapacity  the initial capacity of the ArrayList
    090     * @throws IllegalArgumentException if initial capacity is invalid
    091     */
    092    public GrowthList(final int initialCapacity) {
    093        super(new ArrayList<>(initialCapacity));
    094    }
    095
    096    /**
    097     * Constructor that wraps (not copies).
    098     *
    099     * @param list  the list to decorate, must not be null
    100     * @throws NullPointerException if list is null
    101     */
    102    protected GrowthList(final List<E> list) {
    103        super(list);
    104    }
    105
    106    /**
    107     * Decorate the add method to perform the growth behavior.
    108     * <p>
    109     * If the requested index is greater than the current size, the list will
    110     * grow to the new size. Indices between the old size and the requested
    111     * size will be filled with {@code null}.
    112     * <p>
    113     * If the index is less than the current size, the value will be added to
    114     * the underlying list directly.
    115     * If the index is less than zero, the underlying list is called, which
    116     * will probably throw an IndexOutOfBoundsException.
    117     *
    118     * @param index  the index to add at
    119     * @param element  the object to add at the specified index
    120     * @throws UnsupportedOperationException if the underlying list doesn't implement set
    121     * @throws ClassCastException if the underlying list rejects the element
    122     * @throws IllegalArgumentException if the underlying list rejects the element
    123     */
    124    @Override
    125    public void add(final int index, final E element) {
    126        final int size = decorated().size();
    127        if (index > size) {
    128            decorated().addAll(Collections.<E>nCopies(index - size, null));
    129        }
    130        decorated().add(index, element);
    131    }
    132
    133    /**
    134     * Decorate the addAll method to perform the growth behavior.
    135     * <p>
    136     * If the requested index is greater than the current size, the list will
    137     * grow to the new size. Indices between the old size and the requested
    138     * size will be filled with {@code null}.
    139     * <p>
    140     * If the index is less than the current size, the values will be added to
    141     * the underlying list directly.
    142     * If the index is less than zero, the underlying list is called, which
    143     * will probably throw an IndexOutOfBoundsException.
    144     *
    145     * @param index  the index to add at
    146     * @param coll  the collection to add at the specified index
    147     * @return true if the list changed
    148     * @throws UnsupportedOperationException if the underlying list doesn't implement set
    149     * @throws ClassCastException if the underlying list rejects the element
    150     * @throws IllegalArgumentException if the underlying list rejects the element
    151     */
    152    @Override
    153    public boolean addAll(final int index, final Collection<? extends E> coll) {
    154        final int size = decorated().size();
    155        boolean result = false;
    156        if (index > size) {
    157            decorated().addAll(Collections.<E>nCopies(index - size, null));
    158            result = true;
    159        }
    160        return decorated().addAll(index, coll) || result;
    161    }
    162
    163    /**
    164     * Decorate the set method to perform the growth behavior.
    165     * <p>
    166     * If the requested index is greater than the current size, the list will
    167     * grow to the new size. Indices between the old size and the requested
    168     * size will be filled with {@code null}.
    169     * <p>
    170     * If the index is less than the current size, the value will be set onto
    171     * the underlying list directly.
    172     * If the index is less than zero, the underlying list is called, which
    173     * will probably throw an IndexOutOfBoundsException.
    174     *
    175     * @param index  the index to set
    176     * @param element  the object to set at the specified index
    177     * @return the object previously at that index
    178     * @throws UnsupportedOperationException if the underlying list doesn't implement set
    179     * @throws ClassCastException if the underlying list rejects the element
    180     * @throws IllegalArgumentException if the underlying list rejects the element
    181     */
    182    @Override
    183    public E set(final int index, final E element) {
    184        final int size = decorated().size();
    185        if (index >= size) {
    186            decorated().addAll(Collections.<E>nCopies(index - size + 1, null));
    187        }
    188        return decorated().set(index, element);
    189    }
    190
    191}