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

com.epam.deltix.util.collections.generated.LongArrayList Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2021 EPAM Systems, Inc
 *
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership. Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.epam.deltix.util.collections.generated;


import java.util.AbstractList;
import java.util.Collection;
import java.util.Arrays;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.List;

import com.epam.deltix.util.collections.SafeArrays;
import com.epam.deltix.util.memory.*;
import com.epam.deltix.util.collections.ICapacity;




/**
 * Resizable array of primitive longs. Much more efficient than
 *	keeping a java.util.ArrayList of Long.
 */

public final class LongArrayList extends AbstractList implements List, LongList, Cloneable, java.io.Serializable, MemorySizeEstimator, ICapacity {

    static final long  serialVersionUID = 1L;

    /**
     * Maximum length to which the underlying array can grow. Some VMs reserve some header words in an array.
     */
    private static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     *
     * @serial
     */
    private long elementData[];

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    public long              getSizeInMemory () {
        return (OBJECT_OVERHEAD + SIZE_OF_INT + SIZE_OF_POINTER + EstimatorUtils.getSizeInMemory(elementData));
    }

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param   initialCapacity   the initial capacity of the list.
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
     */
    public LongArrayList(int initialCapacity) {
		super();
        elementData = new long [initialCapacity];
    }

    /**
     * Constructs an empty list.
     */
    public LongArrayList() {
		this(10);
    }

    /**
     * Constructs a list containing the elements of the specified
     * list, in the order they are returned by the collection's
     * iterator.  The ArrayList instance has an initial capacity of
     * the same size of the specified collection.
     *
     * @param list the list whose elements are to be placed into this list.
     */
    public LongArrayList(LongArrayList list) {
        elementData = list.toLongArray();
        size = elementData.length;
    }

     /**
     * Constructs a list containing the elements of the specified
     * list, in the order they are returned by the collection's
     * iterator.  The ArrayList instance has an initial capacity of
     * the same size of the specified collection.
     *
     * @param list the list whose elements are to be placed into this list.
     */
    public LongArrayList(LongList list) {
        elementData = list.toLongArray();
        size = elementData.length;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.  The ArrayList instance has an initial capacity of
     * the same size of the specified collection.
     *
     * @param c the collection whose elements are to be placed into this list.
     */
    public LongArrayList(Collection c) {
        size = c.size ();
		elementData = new long [size];

		Iterator iter = c.iterator ();
        int			idx = 0;

        while (iter.hasNext ())
        	elementData [idx++] = iter.next ();
    }

    public LongArrayList (long [] arr) {
    	size = arr.length;
        elementData = Arrays.copyOf(arr, size); // intrinsic doesn't zero memory
    }

    public LongArrayList (long [] arr, int offset, int length) {
        size = length;
        elementData = Arrays.copyOfRange(arr, offset, offset + length); // intrinsic doesn't zero memory
    }

    /**
     * Trims the capacity of this ArrayList instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an ArrayList instance.
     */
    public void trimToSize() {
		if (size < elementData.length) {
     		elementData = Arrays.copyOf(elementData, size); // intrinsic doesn't zero memory
     		modCount++;
		}
    }

    /**
     * Increases the capacity of this ArrayList instance, if
     * necessary, to ensure  that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity.
     */
    public void ensureCapacity(int minCapacity) {
		if (minCapacity > elementData.length) {
            grow(minCapacity);
        }
    }

    public void ensureCapacityUnsafe(int minCapacity) {
		ensureCapacity(minCapacity); // the same cost
    }

    private void ensureFreeSpace(int required) {
        long requiredCapacity = (long) size + required;

        if (requiredCapacity > elementData.length) {
            grow(requiredCapacity);
        }
    }

    private void grow(long requiredCapacity) {
        if (requiredCapacity > MAX_ARRAY_LENGTH) {
            throw new OutOfMemoryError("required capacity=" + requiredCapacity + " exceeds max");
        }

        int newCapacity = (int) Math.min(MAX_ARRAY_LENGTH,  requiredCapacity  + (requiredCapacity >>> 1)); // 50% for growth
        elementData = Arrays.copyOf(elementData, newCapacity);
        modCount++;
    }

	/**
    * Returns the capacity of this list.
    *
    * @return the capacity of this list.
    */
    public int capacity() {
		return elementData.length;
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return  the number of elements in this list.
     */
    public int size () {
		return size;
    }

    /**
     * Tests if this list has no elements.
     *
     * @return  true if this list has no elements;
     *          false otherwise.
     */
    public boolean isEmpty() {
		return size == 0;
    }

    /**
     * Returns true if this list contains the specified element.
     *
     * @param elem element whose presence in this List is to be tested.
     */
    public boolean contains (Object elem) {
		return indexOf (elem) >= 0;
    }

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of element to return.
     * @return the element at the specified position in this list.
     * @throws    IndexOutOfBoundsException if index is out of range (index
     * 		  < 0 || index >= size()).
     */
    public Long get (int index) {
		return getLong (index);
    }

    /**
     * 

Returns an array containing all of the elements in this list in the * correct order. The runtime type of the returned array is that of the * specified array. If the list fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the runtime * type of the specified array and the size of this list.

* *

If the list fits in the specified array with room to spare (i.e., the * array has more elements than the list), the element in the array * immediately following the end of the collection is set to * null.

* * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list. * @throws ArrayStoreException if the runtime type of a is not a supertype * of Long. */ @SuppressWarnings("unchecked") public T[] toArray(T[] a) { if (a.length < size) { a = Arrays.copyOf(a, size); } for (int i = 0; i < size; i++) { a[i] = (T) new Long(elementData[i]); } if (a.length > size) { a[size] = null; } return a; } /** * Returns true if this list contains the specified element. * * @param elem element whose presence in this List is to be tested. */ public boolean contains (long elem) { return indexOf (elem) >= 0; } /** * Searches for the first occurrence of the given argument, testing * for equality. * * @param elem an object. * @return the index of the first occurrence of the argument in this * list; returns -1 if the object is not found. */ public int indexOf(Object elem) { return (indexOf (((Long) elem).longValue ())); } /** * Returns the index of the last occurrence of the specified long in * this list. * * @param elem the desired element. * @return the index of the last occurrence of the specified long in * this list; returns -1 if the object is not found. */ public int lastIndexOf (Object elem) { return (lastIndexOf (((Long) elem).longValue ())); } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * @throws IndexOutOfBoundsException if index out of range * (index < 0 || index >= size()). */ public Long set (int index, Long element) { return set(index, element.longValue()); } /** * Appends the specified element to the end of this list. * * @param o element to be appended to this list. * @return true (as per the general contract of Collection.add). */ public boolean add (Long o) { return (add (o.longValue ())); } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * @throws IndexOutOfBoundsException if index is out of range * (index < 0 || index > size()). */ public void add (int index, Long element) { add (index, element.longValue ()); } /** * Searches for the first occurrence of the given argument, testing * for equality. * * @param elem an object. * @return the index of the first occurrence of the argument in this * list; returns -1 if the object is not found. */ public int indexOf (long elem) { for (int i = 0; i < size; i++) if (elem == elementData[i]) return i; return -1; } /** * Returns the index of the last occurrence of the specified long in * this list. * * @param elem the desired element. * @return the index of the last occurrence of the specified long in * this list; returns -1 if the object is not found. */ public int lastIndexOf (long elem) { for (int i = size-1; i >= 0; i--) if (elem == elementData [i]) return i; return -1; } /** * Returns a copy of this LongArrayList instance. * * @return a clone of this LongArrayList instance. */ public Object clone () { return new LongArrayList(elementData, 0, size); } /** * Returns an Object array containing all of the elements in this list * in the correct order. * * @return an array containing all of the elements in this list * in the correct order. */ public Object [] toArray() { Object [] result = new Object[size]; return toArray (result); } /** * Returns a long array containing all of the elements in this list * in the correct order. * * @return an array containing all of the elements in this list * in the correct order. */ public long [] toLongArray () { return Arrays.copyOf(elementData, size); } // Positional Access Operations /** * Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * @throws IndexOutOfBoundsException if index is out of range (index * < 0 || index >= size()). */ @SuppressWarnings("unchecked") public long getLong (int index) { rangeCheck(index); return (long) elementData[index]; } /** * Returns the element at the specified position in this list, bypassing * the range check. * @param index index of element to return. * @return the element at the specified position in this list. */ @SuppressWarnings("unchecked") public long getLongNoRangeCheck (int index) { return (long) elementData [index]; } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * @throws IndexOutOfBoundsException if index out of range * (index < 0 || index >= size()). */ @SuppressWarnings("unchecked") public long set (int index, long element) { rangeCheck(index); long oldValue = (long) elementData[index]; elementData[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * * @param d element to be appended to this list. * @return true (as per the general contract of Collection.add). */ public boolean add (long d) { ensureFreeSpace(1); elementData[size++] = d; modCount++; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * @throws IndexOutOfBoundsException if index is out of range * (index < 0 || index > size()). */ public void add (int index, long element) { rangeCheck(index, 0); ensureFreeSpace (1); SafeArrays.safeArrayCopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; modCount++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to removed. * @return the element that was removed from the list. * @throws IndexOutOfBoundsException if index out of range (index * < 0 || index >= size()). */ public Long remove (int index) { return (removeLong (index)); } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to removed. * @return the element that was removed from the list. * @throws IndexOutOfBoundsException if index out of range (index * < 0 || index >= size()). */ @SuppressWarnings("unchecked") public long removeLong (int index) { rangeCheck(index); long oldValue = (long) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) { SafeArrays.safeArrayCopy(elementData, index+1, elementData, index, numMoved); } size--; modCount++; return oldValue; } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { modCount++; size = 0; } /** * Appends all of the elements in the specified Collection to the end of * this list, in the order that they are returned by the * specified Collection's Iterator. The behavior of this operation is * undefined if the specified Collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified Collection is this list, and this * list is nonempty.) * * @param c the elements to be inserted into this list. * @throws IndexOutOfBoundsException if index out of range (index * < 0 || index > size()). */ public boolean addAll (Collection c) { int numNew = c.size(); ensureFreeSpace(numNew); Iterator iter = c.iterator (); for (int i=0; i(index * < 0 || index > size()). */ public boolean addAll (long c[], int offset, int length) { ensureFreeSpace(length); SafeArrays.safeArrayCopy(c, offset, elementData, size, length); size += length; modCount++; return length != 0; } /** Method copies content of this list into the list provided as argument. NOTE: destination list is not cleaned. */ public void copyTo (LongArrayList list) { list.setSize(size); SafeArrays.safeArrayCopy(elementData, 0, list.elementData, 0, size); } /** * Inserts all of the elements in the specified Collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified Collection's iterator. * * @param index index at which to insert first element * from the specified collection. * @param c elements to be inserted into this list. * @throws IndexOutOfBoundsException if index out of range (index * < 0 || index > size()). */ public boolean addAll (Collection c, int index) { rangeCheck(index, 0); int numNew = c.size(); ensureFreeSpace(numNew); int numMoved = size - index; if (numMoved > 0) { SafeArrays.safeArrayCopy(elementData, index, elementData, index + numNew, numMoved); } Iterator iter = c.iterator (); for (int i = 0; i < numNew; i++) { elementData[index++] = iter.next (); } size += numNew; modCount++; return numNew != 0; } /** * Removes from this List all of the elements whose index is between * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding * elements to the left (reduces their index). * This call shortens the list by (toIndex - fromIndex) elements. * (If toIndex==fromIndex, this operation has no effect.) * * @param fromIndex index of first element to be removed. * @param toIndex index after last element to be removed. */ public void removeRange (int fromIndex, int toIndex) { rangeCheck(fromIndex, toIndex - fromIndex); final int numMoved = size - toIndex; SafeArrays.safeArrayCopy(elementData, toIndex, elementData, fromIndex, numMoved); size -= (toIndex - fromIndex); modCount++; } /** * Inserts an uninitialized area at atIndex. Shifts any succeeding * elements to the right by offset (increases their index). * This call lengthens the list by offset elements. * (If offset==0, this operation has no effect.) * * @param atIndex index of first element to be shifted. * @param offset offset to shift by. */ public void insertUnsafe (int atIndex, int offset) { final int newSize = size + offset; ensureCapacity (newSize); SafeArrays.safeArrayCopy(elementData, atIndex, elementData, atIndex + offset, size - atIndex); size = newSize; modCount++; } /** * Inserts and fills an area at atIndex. Shifts any succeeding * elements to the right by offset (increases their index). * This call lengthens the list by offset elements. * (If offset==0, this operation has no effect.) * * @param atIndex index of first element to be shifted. * @param offset offset to shift by. * @param filler value to initialize new elements */ public void insert (int atIndex, int offset, long filler) { final int newSize = size + offset; final int end = atIndex + offset; ensureCapacity (newSize); SafeArrays.safeArrayCopy ( elementData, atIndex, elementData, end, size - atIndex ); for (int ii = atIndex; ii < end; ii++) elementData [ii] = filler; size = newSize; } /** * Check if the given index is in range. If not, throw an appropriate * runtime exception. */ private void rangeCheck(int index) { if (Integer.toUnsignedLong(index) >= size) { // 1 conditional branch instead of 2 throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } } /** * Check if the given range is in range. If not, throw an appropriate * runtime exception. */ private void rangeCheck(int offset, int length) { if (Integer.toUnsignedLong(offset) + Integer.toUnsignedLong(length) > size) { // 1 conditional branch instead of 4 throw new IndexOutOfBoundsException("Offset: " + offset + ", Length: " + length + ", Size: " + size); } } /** * Save the state of the ArrayList instance to a stream (that * is, serialize it). * * @serialData The length of the array backing the ArrayList * instance is emitted (int), followed by all of its elements * (each an Object) in the proper order. */ private synchronized void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out array length s.writeInt(size); // Write out all elements in the proper order. for (int i=0; iArrayList instance from a stream (that is, * deserialize it). */ @SuppressWarnings("unchecked") private synchronized void readObject (java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in array length and allocate array size = s.readInt(); elementData = new long [size]; // Read in all elements in the proper order. for (int i=0; i




© 2015 - 2024 Weber Informatics LLC | Privacy Policy