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

dorkbox.util.collections.IntArray Maven / Gradle / Ivy

The newest version!
/*******************************************************************************
 * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
 *
 * 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.
 */

// from libGDX

package dorkbox.util.collections;


import dorkbox.util.MathUtil;

import java.util.Arrays;

/** A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList. If unordered, this class
 * avoids a memory copy when removing elements (the last element is moved to the removed element's position).
 * @author Nathan Sweet */
public class IntArray {
    public int[] items;
    public int size;
    public boolean ordered;

    /** Creates an ordered array with a capacity of 16. */
    public IntArray () {
        this(true, 16);
    }

    /** Creates an ordered array with the specified capacity. */
    public IntArray (int capacity) {
        this(true, capacity);
    }

    /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
    *           memory copy.
    * @param capacity Any elements added beyond this will cause the backing array to be grown. */
    public IntArray (boolean ordered, int capacity) {
        this.ordered = ordered;
        this.items = new int[capacity];
    }

    /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is
    * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be
    * grown. */
    public IntArray (IntArray array) {
        this.ordered = array.ordered;
        this.size = array.size;
        this.items = new int[this.size];
        System.arraycopy(array.items, 0, this.items, 0, this.size);
    }

    /** Creates a new ordered array containing the elements in the specified array. The capacity is set to the number of elements,
    * so any subsequent elements added will cause the backing array to be grown. */
    public IntArray (int[] array) {
        this(true, array, 0, array.length);
    }

    /** Creates a new array containing the elements in the specified array. The capacity is set to the number of elements, so any
    * subsequent elements added will cause the backing array to be grown.
    * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a
    *           memory copy. */
    public IntArray (boolean ordered, int[] array, int startIndex, int count) {
        this(ordered, array.length);
        this.size = count;
        System.arraycopy(array, startIndex, this.items, 0, count);
    }

    public void add (int value) {
        int[] items = this.items;
        if (this.size == items.length) {
            items = resize(Math.max(8, (int)(this.size * 1.75f)));
        }
        items[this.size++] = value;
    }

    public void addAll (IntArray array) {
        addAll(array, 0, array.size);
    }

    public void addAll (IntArray array, int offset, int length) {
        if (offset + length > array.size) {
            throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size);
        }
        addAll(array.items, offset, length);
    }

    public void addAll (int[] array) {
        addAll(array, 0, array.length);
    }

    public void addAll (int[] array, int offset, int length) {
        int[] items = this.items;
        int sizeNeeded = this.size + length;
        if (sizeNeeded >= items.length) {
            items = resize(Math.max(8, (int)(sizeNeeded * 1.75f)));
        }
        System.arraycopy(array, offset, items, this.size, length);
        this.size += length;
    }

    public int get (int index) {
        if (index >= this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        return this.items[index];
    }

    public void set (int index, int value) {
        if (index >= this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        this.items[index] = value;
    }

    public void insert (int index, int value) {
        if (index > this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        int[] items = this.items;
        if (this.size == items.length) {
            items = resize(Math.max(8, (int)(this.size * 1.75f)));
        }
        if (this.ordered) {
            System.arraycopy(items, index, items, index + 1, this.size - index);
        } else {
            items[this.size] = items[index];
        }
        this.size++;
        items[index] = value;
    }

    public void swap (int first, int second) {
        if (first >= this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(first));
        }
        if (second >= this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(second));
        }
        int[] items = this.items;
        int firstValue = items[first];
        items[first] = items[second];
        items[second] = firstValue;
    }

    public boolean contains (int value) {
        int i = this.size - 1;
        int[] items = this.items;
        while (i >= 0) {
            if (items[i--] == value) {
                return true;
            }
        }
        return false;
    }

    public int indexOf (int value) {
        int[] items = this.items;
        for (int i = 0, n = this.size; i < n; i++) {
            if (items[i] == value) {
                return i;
            }
        }
        return -1;
    }

    public int lastIndexOf (int value) {
        int[] items = this.items;
        for (int i = this.size - 1; i >= 0; i--) {
            if (items[i] == value) {
                return i;
            }
        }
        return -1;
    }

    public boolean removeValue (int value) {
        int[] items = this.items;
        for (int i = 0, n = this.size; i < n; i++) {
            if (items[i] == value) {
                removeIndex(i);
                return true;
            }
        }
        return false;
    }

    /** Removes and returns the item at the specified index. */
    public int removeIndex (int index) {
        if (index >= this.size) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        int[] items = this.items;
        int value = items[index];
        this.size--;
        if (this.ordered) {
            System.arraycopy(items, index + 1, items, index, this.size - index);
        } else {
            items[index] = items[this.size];
        }
        return value;
    }

    /** Removes from this array all of elements contained in the specified array.
    * @return true if this array was modified. */
    public boolean removeAll (IntArray array) {
        int size = this.size;
        int startSize = size;
        int[] items = this.items;
        for (int i = 0, n = array.size; i < n; i++) {
            int item = array.get(i);
            for (int ii = 0; ii < size; ii++) {
                if (item == items[ii]) {
                    removeIndex(ii);
                    size--;
                    break;
                }
            }
        }
        return size != startSize;
    }

    /** Removes and returns the last item. */
    public int pop () {
        return this.items[--this.size];
    }

    /** Returns the last item. */
    public int peek () {
        return this.items[this.size - 1];
    }

    /** Returns the first item. */
    public int first () {
        if (this.size == 0) {
            throw new IllegalStateException("Array is empty.");
        }
        return this.items[0];
    }

    public void clear () {
        this.size = 0;
    }

    /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have
    * been removed, or if it is known that more items will not be added. */
    public void shrink () {
        resize(this.size);
    }

    /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many
    * items to avoid multiple backing array resizes.
    * @return {@link #items} */
    public int[] ensureCapacity (int additionalCapacity) {
        int sizeNeeded = this.size + additionalCapacity;
        if (sizeNeeded >= this.items.length) {
            resize(Math.max(8, sizeNeeded));
        }
        return this.items;
    }

    protected int[] resize (int newSize) {
        int[] newItems = new int[newSize];
        int[] items = this.items;
        System.arraycopy(items, 0, newItems, 0, Math.min(this.size, newItems.length));
        this.items = newItems;
        return newItems;
    }

    public void sort () {
        Arrays.sort(this.items, 0, this.size);
    }

    public void reverse () {
        for (int i = 0, lastIndex = this.size - 1, n = this.size / 2; i < n; i++) {
            int ii = lastIndex - i;
            int temp = this.items[i];
            this.items[i] = this.items[ii];
            this.items[ii] = temp;
        }
    }

    public void shuffle () {
        for (int i = this.size - 1; i >= 0; i--) {
            int ii = MathUtil.randomInt(i);
            int temp = this.items[i];
            this.items[i] = this.items[ii];
            this.items[ii] = temp;
        }
    }

    /** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is
    * taken. */
    public void truncate (int newSize) {
        if (this.size > newSize) {
            this.size = newSize;
        }
    }

    /** Returns a random item from the array, or zero if the array is empty. */
    public int random () {
        if (this.size == 0) {
            return 0;
        }
        return this.items[MathUtil.randomInt(0, this.size - 1)];
    }

    public int[] toArray () {
        int[] array = new int[this.size];
        System.arraycopy(this.items, 0, array, 0, this.size);
        return array;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(this.items);
        result = prime * result + (this.ordered ? 1231 : 1237);
        result = prime * result + this.size;
        return result;
    }

    @Override
    public boolean equals (Object object) {
        if (object == this) {
            return true;
        }
        if (!(object instanceof IntArray)) {
            return false;
        }
        IntArray array = (IntArray)object;
        int n = this.size;
        if (n != array.size) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (this.items[i] != array.items[i]) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String toString () {
        if (this.size == 0) {
            return "[]";
        }
        int[] items = this.items;
        StringBuilder buffer = new StringBuilder(32);
        buffer.append('[');
        buffer.append(items[0]);
        for (int i = 1; i < this.size; i++) {
            buffer.append(", ");
            buffer.append(items[i]);
        }
        buffer.append(']');
        return buffer.toString();
    }

    public String toString (String separator) {
        if (this.size == 0) {
            return "";
        }
        int[] items = this.items;
        StringBuilder buffer = new StringBuilder(32);
        buffer.append(items[0]);
        for (int i = 1; i < this.size; i++) {
            buffer.append(separator);
            buffer.append(items[i]);
        }
        return buffer.toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy