All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.davidmoten.guavamini.Lists Maven / Gradle / Ivy

package com.github.davidmoten.guavamini;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import com.github.davidmoten.guavamini.annotations.VisibleForTesting;

public final class Lists {

    private Lists() {
        // cannot instantiate
    }

    public static  ArrayList newArrayList(E... elements) {
        Preconditions.checkNotNull(elements);
        // Avoid integer overflow when a large array is passed in
        int capacity = computeArrayListCapacity(elements.length);
        ArrayList list = new ArrayList(capacity);
        Collections.addAll(list, elements);
        return list;
    }

    @VisibleForTesting
    static int computeArrayListCapacity(int arraySize) {
        Preconditions.checkArgument(arraySize >= 0, "arraySize must be non-negative");

        // TODO(kevinb): Figure out the right behavior, and document it
        return saturatedCast(5L + arraySize + (arraySize / 10));
    }

    /**
     * Returns the {@code int} nearest in value to {@code value}.
     *
     * @param value
     *            any {@code long} value
     * @return the same value cast to {@code int} if it is in the range of the
     *         {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
     *         or {@link Integer#MIN_VALUE} if it is too small
     */
    @VisibleForTesting
    static int saturatedCast(long value) {
        if (value > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (value < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int) value;
    }

    public static  ArrayList newArrayList() {
        return new ArrayList();
    }

    public static  ArrayList newArrayList(Iterable elements) {
        Preconditions.checkNotNull(elements); // for GWT
        // Let ArrayList's sizing logic work, if possible
        return (elements instanceof Collection) ? new ArrayList(Collections2.cast(elements))
                : newArrayList(elements.iterator());
    }

    public static  ArrayList newArrayList(Iterator elements) {
        ArrayList list = newArrayList();
        Iterators.addAll(list, elements);
        return list;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy