{
/**
* Constructs a new instance of this AbstractCollection.
*/
protected AbstractCollection() {
}
public boolean add(E object) {
throw new UnsupportedOperationException();
}
/**
* Attempts to add all of the objects contained in {@code collection}
* to the contents of this {@code Collection} (optional). This implementation
* iterates over the given {@code Collection} and calls {@code add} for each
* element. If any of these calls return {@code true}, then {@code true} is
* returned as result of this method call, {@code false} otherwise. If this
* {@code Collection} does not support adding elements, an {@code
* UnsupportedOperationException} is thrown.
*
* If the passed {@code Collection} is changed during the process of adding elements
* to this {@code Collection}, the behavior depends on the behavior of the passed
* {@code Collection}.
*
* @param collection
* the collection of objects.
* @return {@code true} if this {@code Collection} is modified, {@code false}
* otherwise.
* @throws UnsupportedOperationException
* if adding to this {@code Collection} is not supported.
* @throws ClassCastException
* if the class of an object is inappropriate for this
* {@code Collection}.
* @throws IllegalArgumentException
* if an object cannot be added to this {@code Collection}.
* @throws NullPointerException
* if {@code collection} is {@code null}, or if it contains
* {@code null} elements and this {@code Collection} does not support
* such elements.
*/
public boolean addAll(Collection extends E> collection) {
boolean result = false;
Iterator extends E> it = collection.iterator();
while (it.hasNext()) {
if (add(it.next())) {
result = true;
}
}
return result;
}
/**
* Removes all elements from this {@code Collection}, leaving it empty (optional).
* This implementation iterates over this {@code Collection} and calls the {@code
* remove} method on each element. If the iterator does not support removal
* of elements, an {@code UnsupportedOperationException} is thrown.
*
* Concrete implementations usually can clear a {@code Collection} more efficiently
* and should therefore overwrite this method.
*
* @throws UnsupportedOperationException
* it the iterator does not support removing elements from
* this {@code Collection}
* @see #iterator
* @see #isEmpty
* @see #size
*/
public void clear() {
Iterator it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
/**
* Tests whether this {@code Collection} contains the specified object. This
* implementation iterates over this {@code Collection} and tests, whether any
* element is equal to the given object. If {@code object != null} then
* {@code object.equals(e)} is called for each element {@code e} returned by
* the iterator until the element is found. If {@code object == null} then
* each element {@code e} returned by the iterator is compared with the test
* {@code e == null}.
*
* @param object
* the object to search for.
* @return {@code true} if object is an element of this {@code Collection}, {@code
* false} otherwise.
* @throws ClassCastException
* if the object to look for isn't of the correct type.
* @throws NullPointerException
* if the object to look for is {@code null} and this
* {@code Collection} doesn't support {@code null} elements.
*/
public boolean contains(Object object) {
Iterator it = iterator();
if (object != null) {
while (it.hasNext()) {
if (object.equals(it.next())) {
return true;
}
}
} else {
while (it.hasNext()) {
if (it.next() == null) {
return true;
}
}
}
return false;
}
/**
* Tests whether this {@code Collection} contains all objects contained in the
* specified {@code Collection}. This implementation iterates over the specified
* {@code Collection}. If one element returned by the iterator is not contained in
* this {@code Collection}, then {@code false} is returned; {@code true} otherwise.
*
* @param collection
* the collection of objects.
* @return {@code true} if all objects in the specified {@code Collection} are
* elements of this {@code Collection}, {@code false} otherwise.
* @throws ClassCastException
* if one or more elements of {@code collection} isn't of the
* correct type.
* @throws NullPointerException
* if {@code collection} contains at least one {@code null}
* element and this {@code Collection} doesn't support {@code null}
* elements.
* @throws NullPointerException
* if {@code collection} is {@code null}.
*/
public boolean containsAll(Collection> collection) {
Iterator> it = collection.iterator();
while (it.hasNext()) {
if (!contains(it.next())) {
return false;
}
}
return true;
}
/**
* Returns if this {@code Collection} contains no elements. This implementation
* tests, whether {@code size} returns 0.
*
* @return {@code true} if this {@code Collection} has no elements, {@code false}
* otherwise.
*
* @see #size
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns an instance of {@link Iterator} that may be used to access the
* objects contained by this {@code Collection}. The order in which the elements are
* returned by the {@link Iterator} is not defined unless the instance of the
* {@code Collection} has a defined order. In that case, the elements are returned in that order.
*
* In this class this method is declared abstract and has to be implemented
* by concrete {@code Collection} implementations.
*
* @return an iterator for accessing the {@code Collection} contents.
*/
public abstract Iterator iterator();
/**
* Removes one instance of the specified object from this {@code Collection} if one
* is contained (optional). This implementation iterates over this
* {@code Collection} and tests for each element {@code e} returned by the iterator,
* whether {@code e} is equal to the given object. If {@code object != null}
* then this test is performed using {@code object.equals(e)}, otherwise
* using {@code object == null}. If an element equal to the given object is
* found, then the {@code remove} method is called on the iterator and
* {@code true} is returned, {@code false} otherwise. If the iterator does
* not support removing elements, an {@code UnsupportedOperationException}
* is thrown.
*
* @param object
* the object to remove.
* @return {@code true} if this {@code Collection} is modified, {@code false}
* otherwise.
* @throws UnsupportedOperationException
* if removing from this {@code Collection} is not supported.
* @throws ClassCastException
* if the object passed is not of the correct type.
* @throws NullPointerException
* if {@code object} is {@code null} and this {@code Collection}
* doesn't support {@code null} elements.
*/
public boolean remove(Object object) {
Iterator> it = iterator();
if (object != null) {
while (it.hasNext()) {
if (object.equals(it.next())) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (it.next() == null) {
it.remove();
return true;
}
}
}
return false;
}
/**
* Removes all occurrences in this {@code Collection} of each object in the
* specified {@code Collection} (optional). After this method returns none of the
* elements in the passed {@code Collection} can be found in this {@code Collection}
* anymore.
*
* This implementation iterates over this {@code Collection} and tests for each
* element {@code e} returned by the iterator, whether it is contained in
* the specified {@code Collection}. If this test is positive, then the {@code
* remove} method is called on the iterator. If the iterator does not
* support removing elements, an {@code UnsupportedOperationException} is
* thrown.
*
* @param collection
* the collection of objects to remove.
* @return {@code true} if this {@code Collection} is modified, {@code false}
* otherwise.
* @throws UnsupportedOperationException
* if removing from this {@code Collection} is not supported.
* @throws ClassCastException
* if one or more elements of {@code collection} isn't of the
* correct type.
* @throws NullPointerException
* if {@code collection} contains at least one {@code null}
* element and this {@code Collection} doesn't support {@code null}
* elements.
* @throws NullPointerException
* if {@code collection} is {@code null}.
*/
public boolean removeAll(Collection> collection) {
boolean result = false;
Iterator> it = iterator();
while (it.hasNext()) {
if (collection.contains(it.next())) {
it.remove();
result = true;
}
}
return result;
}
/**
* Removes all objects from this {@code Collection} that are not also found in the
* {@code Collection} passed (optional). After this method returns this {@code Collection}
* will only contain elements that also can be found in the {@code Collection}
* passed to this method.
*
* This implementation iterates over this {@code Collection} and tests for each
* element {@code e} returned by the iterator, whether it is contained in
* the specified {@code Collection}. If this test is negative, then the {@code
* remove} method is called on the iterator. If the iterator does not
* support removing elements, an {@code UnsupportedOperationException} is
* thrown.
*
* @param collection
* the collection of objects to retain.
* @return {@code true} if this {@code Collection} is modified, {@code false}
* otherwise.
* @throws UnsupportedOperationException
* if removing from this {@code Collection} is not supported.
* @throws ClassCastException
* if one or more elements of {@code collection}
* isn't of the correct type.
* @throws NullPointerException
* if {@code collection} contains at least one
* {@code null} element and this {@code Collection} doesn't support
* {@code null} elements.
* @throws NullPointerException
* if {@code collection} is {@code null}.
*/
public boolean retainAll(Collection> collection) {
boolean result = false;
Iterator> it = iterator();
while (it.hasNext()) {
if (!collection.contains(it.next())) {
it.remove();
result = true;
}
}
return result;
}
/**
* Returns a count of how many objects this {@code Collection} contains.
*
* In this class this method is declared abstract and has to be implemented
* by concrete {@code Collection} implementations.
*
* @return how many objects this {@code Collection} contains, or {@code Integer.MAX_VALUE}
* if there are more than {@code Integer.MAX_VALUE} elements in this
* {@code Collection}.
*/
public abstract int size();
public Object[] toArray() {
int size = size(), index = 0;
Iterator> it = iterator();
Object[] array = new Object[size];
while (index < size) {
array[index++] = it.next();
}
return array;
}
@SuppressWarnings("unchecked")
public T[] toArray(T[] contents) {
int size = size(), index = 0;
if (size > contents.length) {
Class> ct = contents.getClass().getComponentType();
contents = (T[]) Array.newInstance(ct, size);
}
for (E entry : this) {
contents[index++] = (T) entry;
}
if (index < contents.length) {
contents[index] = null;
}
return contents;
}
/**
* Returns the string representation of this {@code Collection}. The presentation
* has a specific format. It is enclosed by square brackets ("[]"). Elements
* are separated by ', ' (comma and space).
*
* @return the string representation of this {@code Collection}.
*/
@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder buffer = new StringBuilder(size() * 16);
buffer.append('[');
Iterator> it = iterator();
while (it.hasNext()) {
Object next = it.next();
if (next != this) {
buffer.append(next);
} else {
buffer.append("(this Collection)");
}
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append(']');
return buffer.toString();
}
}
================================================
FILE: orm-library/src/main/java/net/tsz/afinal/core/ArrayDeque.java
================================================
/*
* Written by Josh Bloch of Google Inc. and released to the public domain,
* as explained at http://creativecommons.org/licenses/publicdomain.
*/
package net.tsz.afinal.core;
// BEGIN android-note
// removed link to collections framework docs
// END android-note
import java.io.*;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Resizable-array implementation of the {@link Deque} interface. Array
* deques have no capacity restrictions; they grow as necessary to support
* usage. They are not thread-safe; in the absence of external
* synchronization, they do not support concurrent access by multiple threads.
* Null elements are prohibited. This class is likely to be faster than
* {@link Stack} when used as a stack, and faster than {@link LinkedList}
* when used as a queue.
*
* Most ArrayDeque operations run in amortized constant time.
* Exceptions include {@link #remove(Object) remove}, {@link
* #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
* removeLastOccurrence}, {@link #contains contains}, {@link #iterator
* iterator.remove()}, and the bulk operations, all of which run in linear
* time.
*
*
The iterators returned by this class's iterator method are
* fail-fast: If the deque is modified at any time after the iterator
* is created, in any way except through the iterator's own remove
* method, the iterator will generally throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
*
Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw ConcurrentModificationException on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: the fail-fast behavior of iterators
* should be used only to detect bugs.
*
*
This class and its iterator implement all of the
* optional methods of the {@link Collection} and {@link
* Iterator} interfaces.
*
* @author Josh Bloch and Doug Lea
* @since 1.6
* @param the type of elements held in this collection
*/
public class ArrayDeque extends AbstractCollection implements Deque, Cloneable, Serializable
{
/**
* The array in which the elements of the deque are stored.
* The capacity of the deque is the length of this array, which is
* always a power of two. The array is never allowed to become
* full, except transiently within an addX method where it is
* resized (see doubleCapacity) immediately upon becoming full,
* thus avoiding head and tail wrapping around to equal each
* other. We also guarantee that all array cells not holding
* deque elements are always null.
*/
private transient E[] elements;
/**
* The index of the element at the head of the deque (which is the
* element that would be removed by remove() or pop()); or an
* arbitrary number equal to tail if the deque is empty.
*/
private transient int head;
/**
* The index at which the next element would be added to the tail
* of the deque (via addLast(E), add(E), or push(E)).
*/
private transient int tail;
/**
* The minimum capacity that we'll use for a newly created deque.
* Must be a power of 2.
*/
private static final int MIN_INITIAL_CAPACITY = 8;
// ****** Array allocation and resizing utilities ******
/**
* Allocate empty array to hold the given number of elements.
*
* @param numElements the number of elements to hold
*/
@SuppressWarnings("unchecked")
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = (E[]) new Object[initialCapacity];
}
/**
* Double the capacity of this deque. Call only when full, i.e.,
* when head and tail have wrapped around to become equal.
*/
@SuppressWarnings("unchecked")
private void doubleCapacity() {
assert head == tail;
int p = head;
int n = elements.length;
int r = n - p; // number of elements to the right of p
int newCapacity = n << 1;
if (newCapacity < 0)
throw new IllegalStateException("Sorry, deque too big");
Object[] a = new Object[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = (E[])a;
head = 0;
tail = n;
}
/**
* Copies the elements from our element array into the specified array,
* in order (from first to last element in the deque). It is assumed
* that the array is large enough to hold all elements in the deque.
*
* @return its argument
*/
private T[] copyElements(T[] a) {
if (head < tail) {
System.arraycopy(elements, head, a, 0, size());
} else if (head > tail) {
int headPortionLen = elements.length - head;
System.arraycopy(elements, head, a, 0, headPortionLen);
System.arraycopy(elements, 0, a, headPortionLen, tail);
}
return a;
}
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold 16 elements.
*/
@SuppressWarnings("unchecked")
public ArrayDeque() {
elements = (E[]) new Object[16];
}
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold the specified number of elements.
*
* @param numElements lower bound on initial capacity of the deque
*/
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
/**
* Constructs a deque containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator. (The first element returned by the collection's
* iterator becomes the first element, or front of the
* deque.)
*
* @param c the collection whose elements are to be placed into the deque
* @throws NullPointerException if the specified collection is null
*/
public ArrayDeque(Collection extends E> c) {
allocateElements(c.size());
addAll(c);
}
// The main insertion and extraction methods are addFirst,
// addLast, pollFirst, pollLast. The other methods are defined in
// terms of these.
/**
* Inserts the specified element at the front of this deque.
*
* @param e the element to add
* @throws NullPointerException if the specified element is null
*/
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
/**
* Inserts the specified element at the end of this deque.
*
* This method is equivalent to {@link #add}.
*
* @param e the element to add
* @throws NullPointerException if the specified element is null
*/
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
/**
* Inserts the specified element at the front of this deque.
*
* @param e the element to add
* @return true (as specified by {@link Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this deque.
*
* @param e the element to add
* @return true (as specified by {@link Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
E x = pollFirst();
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
E x = pollLast();
if (x == null)
throw new NoSuchElementException();
return x;
}
public E pollFirst() {
int h = head;
E result = elements[h]; // Element is null if deque empty
if (result == null)
return null;
elements[h] = null; // Must null out slot
head = (h + 1) & (elements.length - 1);
return result;
}
public E pollLast() {
int t = (tail - 1) & (elements.length - 1);
E result = elements[t];
if (result == null)
return null;
elements[t] = null;
tail = t;
return result;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
E x = elements[head];
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
E x = elements[(tail - 1) & (elements.length - 1)];
if (x == null)
throw new NoSuchElementException();
return x;
}
public E peekFirst() {
return elements[head]; // elements[head] is null if deque empty
}
public E peekLast() {
return elements[(tail - 1) & (elements.length - 1)];
}
/**
* Removes the first occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element e such that
* o.equals(e) (if such an element exists).
* Returns true if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return true if the deque contained the specified element
*/
public boolean removeFirstOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i + 1) & mask;
}
return false;
}
/**
* Removes the last occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
* More formally, removes the last element e such that
* o.equals(e) (if such an element exists).
* Returns true if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return true if the deque contained the specified element
*/
public boolean removeLastOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = (tail - 1) & mask;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i - 1) & mask;
}
return false;
}
// *** Queue methods ***
/**
* Inserts the specified element at the end of this deque.
*
*
This method is equivalent to {@link #addLast}.
*
* @param e the element to add
* @return true (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
addLast(e);
return true;
}
/**
* Inserts the specified element at the end of this deque.
*
*
This method is equivalent to {@link #offerLast}.
*
* @param e the element to add
* @return true (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* Retrieves and removes the head of the queue represented by this deque.
*
* This method differs from {@link #poll poll} only in that it throws an
* exception if this deque is empty.
*
*
This method is equivalent to {@link #removeFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException {@inheritDoc}
*/
public E remove() {
return removeFirst();
}
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), or returns
* null if this deque is empty.
*
*
This method is equivalent to {@link #pollFirst}.
*
* @return the head of the queue represented by this deque, or
* null if this deque is empty
*/
public E poll() {
return pollFirst();
}
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque. This method differs from {@link #peek peek} only in
* that it throws an exception if this deque is empty.
*
*
This method is equivalent to {@link #getFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException {@inheritDoc}
*/
public E element() {
return getFirst();
}
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque, or returns null if this deque is empty.
*
*
This method is equivalent to {@link #peekFirst}.
*
* @return the head of the queue represented by this deque, or
* null if this deque is empty
*/
public E peek() {
return peekFirst();
}
// *** Stack methods ***
/**
* Pushes an element onto the stack represented by this deque. In other
* words, inserts the element at the front of this deque.
*
*
This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @throws NullPointerException if the specified element is null
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this deque. In other
* words, removes and returns the first element of this deque.
*
*
This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this deque (which is the top
* of the stack represented by this deque)
* @throws NoSuchElementException {@inheritDoc}
*/
public E pop() {
return removeFirst();
}
private void checkInvariants() {
assert elements[tail] == null;
assert head == tail ? elements[head] == null :
(elements[head] != null &&
elements[(tail - 1) & (elements.length - 1)] != null);
assert elements[(head - 1) & (elements.length - 1)] == null;
}
/**
* Removes the element at the specified position in the elements array,
* adjusting head and tail as necessary. This can result in motion of
* elements backwards or forwards in the array.
*
*
This method is called delete rather than remove to emphasize
* that its semantics differ from those of {@link List#remove(int)}.
*
* @return true if elements moved backwards
*/
private boolean delete(int i) {
checkInvariants();
final E[] elements = this.elements;
final int mask = elements.length - 1;
final int h = head;
final int t = tail;
final int front = (i - h) & mask;
final int back = (t - i) & mask;
// Invariant: head <= i < tail mod circularity
if (front >= ((t - h) & mask))
throw new ConcurrentModificationException();
// Optimize for least element motion
if (front < back) {
if (h <= i) {
System.arraycopy(elements, h, elements, h + 1, front);
} else { // Wrap around
System.arraycopy(elements, 0, elements, 1, i);
elements[0] = elements[mask];
System.arraycopy(elements, h, elements, h + 1, mask - h);
}
elements[h] = null;
head = (h + 1) & mask;
return false;
} else {
if (i < t) { // Copy the null tail as well
System.arraycopy(elements, i + 1, elements, i, back);
tail = t - 1;
} else { // Wrap around
System.arraycopy(elements, i + 1, elements, i, mask - i);
elements[mask] = elements[0];
System.arraycopy(elements, 1, elements, 0, t);
tail = (t - 1) & mask;
}
return true;
}
}
// *** Collection Methods ***
/**
* Returns the number of elements in this deque.
*
* @return the number of elements in this deque
*/
public int size() {
return (tail - head) & (elements.length - 1);
}
/**
* Returns true if this deque contains no elements.
*
* @return true if this deque contains no elements
*/
public boolean isEmpty() {
return head == tail;
}
/**
* Returns an iterator over the elements in this deque. The elements
* will be ordered from first (head) to last (tail). This is the same
* order that elements would be dequeued (via successive calls to
* {@link #remove} or popped (via successive calls to {@link #pop}).
*
* @return an iterator over the elements in this deque
*/
public Iterator iterator() {
return new DeqIterator();
}
public Iterator descendingIterator() {
return new DescendingIterator();
}
private class DeqIterator implements Iterator {
/**
* Index of element to be returned by subsequent call to next.
*/
private int cursor = head;
/**
* Tail recorded at construction (also in remove), to stop
* iterator and also to check for comodification.
*/
private int fence = tail;
/**
* Index of element returned by most recent call to next.
* Reset to -1 if element is deleted by a call to remove.
*/
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
E result = elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
if (tail != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
cursor = (cursor + 1) & (elements.length - 1);
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (delete(lastRet)) { // if left-shifted, undo increment in next()
cursor = (cursor - 1) & (elements.length - 1);
fence = tail;
}
lastRet = -1;
}
}
private class DescendingIterator implements Iterator {
/*
* This class is nearly a mirror-image of DeqIterator, using
* tail instead of head for initial cursor, and head instead of
* tail for fence.
*/
private int cursor = tail;
private int fence = head;
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
cursor = (cursor - 1) & (elements.length - 1);
E result = elements[cursor];
if (head != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (!delete(lastRet)) {
cursor = (cursor + 1) & (elements.length - 1);
fence = head;
}
lastRet = -1;
}
}
/**
* Returns true if this deque contains the specified element.
* More formally, returns true if and only if this deque contains
* at least one element e such that o.equals(e).
*
* @param o object to be checked for containment in this deque
* @return true if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x))
return true;
i = (i + 1) & mask;
}
return false;
}
/**
* Removes a single instance of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element e such that
* o.equals(e) (if such an element exists).
* Returns true if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* This method is equivalent to {@link #removeFirstOccurrence}.
*
* @param o element to be removed from this deque, if present
* @return true if this deque contained the specified element
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Removes all of the elements from this deque.
* The deque will be empty after this call returns.
*/
public void clear() {
int h = head;
int t = tail;
if (h != t) { // clear all cells
head = tail = 0;
int i = h;
int mask = elements.length - 1;
do {
elements[i] = null;
i = (i + 1) & mask;
} while (i != t);
}
}
/**
* Returns an array containing all of the elements in this deque
* in proper sequence (from first to last element).
*
*
The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
*
This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
return copyElements(new Object[size()]);
}
/**
* Returns an array containing all of the elements in this deque in
* proper sequence (from first to last element); the runtime type of the
* returned array is that of the specified array. If the deque 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 deque.
*
*
If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* null.
*
*
Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
*
Suppose x is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of String:
*
*
* String[] y = x.toArray(new String[0]);
*
* Note that toArray(new Object[0]) is identical in function to
* toArray().
*
* @param a the array into which the elements of the deque 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 all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
int size = size();
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
copyElements(a);
if (a.length > size)
a[size] = null;
return a;
}
// *** Object methods ***
/**
* Returns a copy of this deque.
*
* @return a copy of this deque
*/
public ArrayDeque clone() {
try {
@SuppressWarnings("unchecked")
ArrayDeque result = (ArrayDeque) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
/**
* Appease the serialization gods.
*/
private static final long serialVersionUID = 2340985798034038923L;
/**
* Serialize this deque.
*
* @serialData The current size (int) of the deque,
* followed by all of its elements (each an object reference) in
* first-to-last order.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// Write out size
s.writeInt(size());
// Write out elements in order.
int mask = elements.length - 1;
for (int i = head; i != tail; i = (i + 1) & mask)
s.writeObject(elements[i]);
}
/**
* Deserialize this deque.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in size and allocate array
int size = s.readInt();
allocateElements(size);
head = 0;
tail = size;
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
elements[i] = (E)s.readObject();
}
}
================================================
FILE: orm-library/src/main/java/net/tsz/afinal/core/Arrays.java
================================================
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 net.tsz.afinal.core;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* {@code Arrays} contains static methods which operate on arrays.
*
* @since 1.2
*/
public class Arrays {
private static class ArrayList extends AbstractList implements
List, Serializable, RandomAccess {
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] storage) {
if (storage == null) {
throw new NullPointerException();
}
a = storage;
}
@Override
public boolean contains(Object object) {
if (object != null) {
for (E element : a) {
if (object.equals(element)) {
return true;
}
}
} else {
for (E element : a) {
if (element == null) {
return true;
}
}
}
return false;
}
@Override
public E get(int location) {
try {
return a[location];
} catch (ArrayIndexOutOfBoundsException e) {
// throw java.util.ArrayList.throwIndexOutOfBoundsException(location, a.length);
throw e;
}
}
@Override
public int indexOf(Object object) {
if (object != null) {
for (int i = 0; i < a.length; i++) {
if (object.equals(a[i])) {
return i;
}
}
} else {
for (int i = 0; i < a.length; i++) {
if (a[i] == null) {
return i;
}
}
}
return -1;
}
@Override
public int lastIndexOf(Object object) {
if (object != null) {
for (int i = a.length - 1; i >= 0; i--) {
if (object.equals(a[i])) {
return i;
}
}
} else {
for (int i = a.length - 1; i >= 0; i--) {
if (a[i] == null) {
return i;
}
}
}
return -1;
}
@Override
public E set(int location, E object) {
E result = a[location];
a[location] = object;
return result;
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return a.clone();
}
@SuppressWarnings("unchecked")
@Override
public T[] toArray(T[] contents) {
int size = size();
if (size > contents.length) {
Class> ct = contents.getClass().getComponentType();
contents = (T[]) Array.newInstance(ct, size);
}
System.arraycopy(a, 0, contents, 0, size);
if (size < contents.length) {
contents[size] = null;
}
return contents;
}
}
private Arrays() {
/* empty */
}
/**
* Returns a {@code List} of the objects in the specified array. The size of the
* {@code List} cannot be modified, i.e. adding and removing are unsupported, but
* the elements can be set. Setting an element modifies the underlying
* array.
*
* @param array
* the array.
* @return a {@code List} of the elements of the specified array.
*/
public static List asList(T... array) {
return new ArrayList(array);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(byte[] array, byte value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(byte[] array, int startIndex, int endIndex, byte value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
byte midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(char[] array, char value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(char[] array, int startIndex, int endIndex, char value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
char midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(double[] array, double value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(double[] array, int startIndex, int endIndex, double value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
double midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else if (midVal != 0 && midVal == value) {
return mid; // value found
} else { // Either midVal and value are == 0 or at least one is NaN
long midValBits = Double.doubleToLongBits(midVal);
long valueBits = Double.doubleToLongBits(value);
if (midValBits < valueBits) {
lo = mid + 1; // (-0.0, 0.0) or (not NaN, NaN); midVal < val
} else if (midValBits > valueBits) {
hi = mid - 1; // (0.0, -0.0) or (NaN, not NaN); midVal > val
} else {
return mid; // bit patterns are equal; value found
}
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(float[] array, float value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(float[] array, int startIndex, int endIndex, float value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
float midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else if (midVal != 0 && midVal == value) {
return mid; // value found
} else { // Either midVal and value are == 0 or at least one is NaN
int midValBits = Float.floatToIntBits(midVal);
int valueBits = Float.floatToIntBits(value);
if (midValBits < valueBits) {
lo = mid + 1; // (-0.0, 0.0) or (not NaN, NaN); midVal < val
} else if (midValBits > valueBits) {
hi = mid - 1; // (0.0, -0.0) or (NaN, not NaN); midVal > val
} else {
return mid; // bit patterns are equal; value found
}
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(int[] array, int value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(int[] array, int startIndex, int endIndex, int value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
int midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(long[] array, long value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(long[] array, int startIndex, int endIndex, long value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
long midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws ClassCastException
* if an element in the array or the search element does not
* implement {@code Comparable}, or cannot be compared to each other.
*/
public static int binarySearch(Object[] array, Object value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws ClassCastException
* if an element in the array or the search element does not
* implement {@code Comparable}, or cannot be compared to each other.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
@SuppressWarnings("unchecked")
public static int binarySearch(Object[] array, int startIndex, int endIndex, Object value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
@SuppressWarnings("rawtypes")
int midValCmp = ((Comparable) array[mid]).compareTo(value);
if (midValCmp < 0) {
lo = mid + 1;
} else if (midValCmp > 0) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* using {@code comparator} to compare elements.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @param comparator the {@code Comparator} used to compare the elements.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws ClassCastException
* if an element in the array or the search element does not
* implement {@code Comparable}, or cannot be compared to each other.
*/
public static int binarySearch(T[] array, T value, Comparator super T> comparator) {
return binarySearch(array, 0, array.length, value, comparator);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive),
* using {@code comparator} to compare elements.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @param comparator the {@code Comparator} used to compare the elements.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws ClassCastException
* if an element in the array or the search element does not
* implement {@code Comparable}, or cannot be compared to each other.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(T[] array, int startIndex, int endIndex, T value,
Comparator super T> comparator) {
if (comparator == null) {
return binarySearch(array, startIndex, endIndex, value);
}
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
int midValCmp = comparator.compare(array[mid], value);
if (midValCmp < 0) {
lo = mid + 1;
} else if (midValCmp > 0) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array}.
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
*/
public static int binarySearch(short[] array, short value) {
return binarySearch(array, 0, array.length, value);
}
/**
* Performs a binary search for {@code value} in the ascending sorted array {@code array},
* in the range specified by fromIndex (inclusive) and toIndex (exclusive).
* Searching in an unsorted array has an undefined result. It's also undefined which element
* is found if there are multiple occurrences of the same element.
*
* @param array the sorted array to search.
* @param startIndex the inclusive start index.
* @param endIndex the exclusive start index.
* @param value the element to find.
* @return the non-negative index of the element, or a negative index which
* is {@code -index - 1} where the element would be inserted.
* @throws IllegalArgumentException if {@code startIndex > endIndex}
* @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length}
* @since 1.6
*/
public static int binarySearch(short[] array, int startIndex, int endIndex, short value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
short midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
private static void checkBinarySearchBounds(int startIndex, int endIndex, int length) {
if (startIndex > endIndex) {
throw new IllegalArgumentException();
}
if (startIndex < 0 || endIndex > length) {
throw new ArrayIndexOutOfBoundsException();
}
}
/**
* Fills the specified array with the specified element.
*
* @param array
* the {@code byte} array to fill.
* @param value
* the {@code byte} element.
*/
public static void fill(byte[] array, byte value) {
for (int i = 0; i < array.length; i++) {
array[i] = value;
}
}
/**
* Fills the specified array with the specified element.
*
* @param array
* the {@code int} array to fill.
* @param value
* the {@code int} element.
*/
public static void fill(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
array[i] = value;
}
}
/**
* Fills the specified array with the specified element.
*
* @param array
* the {@code boolean} array to fill.
* @param value
* the {@code boolean} element.
*/
public static void fill(boolean[] array, boolean value) {
for (int i = 0; i < array.length; i++) {
array[i] = value;
}
}
/**
* Fills the specified array with the specified element.
*
* @param array
* the {@code Object} array to fill.
* @param value
* the {@code Object} element.
*/
public static void fill(Object[] array, Object value) {
for (int i = 0; i < array.length; i++) {
array[i] = value;
}
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code boolean} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Boolean} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (boolean element : array) {
// 1231, 1237 are hash code values for boolean value
hashCode = 31 * hashCode + (element ? 1231 : 1237);
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* not-null {@code int} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Integer} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(int[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (int element : array) {
// the hash code value for integer value is integer value itself
hashCode = 31 * hashCode + element;
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code short} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Short} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(short[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (short element : array) {
// the hash code value for short value is its integer value
hashCode = 31 * hashCode + element;
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code char} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Character} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(char[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (char element : array) {
// the hash code value for char value is its integer value
hashCode = 31 * hashCode + element;
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code byte} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Byte} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(byte[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (byte element : array) {
// the hash code value for byte value is its integer value
hashCode = 31 * hashCode + element;
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code long} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Long} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(long[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (long elementValue : array) {
/*
* the hash code value for long value is (int) (value ^ (value >>>
* 32))
*/
hashCode = 31 * hashCode
+ (int) (elementValue ^ (elementValue >>> 32));
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code float} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Float} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(float[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (float element : array) {
/*
* the hash code value for float value is
* Float.floatToIntBits(value)
*/
hashCode = 31 * hashCode + Float.floatToIntBits(element);
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. For any two
* {@code double} arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the
* {@link List#hashCode()} method which is invoked on a {@link List}
* containing a sequence of {@link Double} instances representing the
* elements of array in the same order. If the array is {@code null}, the return
* value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(double[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (double element : array) {
long v = Double.doubleToLongBits(element);
/*
* the hash code value for double value is (int) (v ^ (v >>> 32))
* where v = Double.doubleToLongBits(value)
*/
hashCode = 31 * hashCode + (int) (v ^ (v >>> 32));
}
return hashCode;
}
/**
* Returns a hash code based on the contents of the given array. If the
* array contains other arrays as its elements, the hash code is based on
* their identities not their contents. So it is acceptable to invoke this
* method on an array that contains itself as an element, either directly or
* indirectly.
*
* For any two arrays {@code a} and {@code b}, if
* {@code Arrays.equals(a, b)} returns {@code true}, it means
* that the return value of {@code Arrays.hashCode(a)} equals
* {@code Arrays.hashCode(b)}.
*
* The value returned by this method is the same value as the method
* Arrays.asList(array).hashCode(). If the array is {@code null}, the return value
* is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int hashCode(Object[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (Object element : array) {
int elementHashCode;
if (element == null) {
elementHashCode = 0;
} else {
elementHashCode = (element).hashCode();
}
hashCode = 31 * hashCode + elementHashCode;
}
return hashCode;
}
/**
* Returns a hash code based on the "deep contents" of the given array. If
* the array contains other arrays as its elements, the hash code is based
* on their contents not their identities. So it is not acceptable to invoke
* this method on an array that contains itself as an element, either
* directly or indirectly.
*
* For any two arrays {@code a} and {@code b}, if
* {@code Arrays.deepEquals(a, b)} returns {@code true}, it
* means that the return value of {@code Arrays.deepHashCode(a)} equals
* {@code Arrays.deepHashCode(b)}.
*
* The computation of the value returned by this method is similar to that
* of the value returned by {@link List#hashCode()} invoked on a
* {@link List} containing a sequence of instances representing the
* elements of array in the same order. The difference is: If an element e
* of array is itself an array, its hash code is computed by calling the
* appropriate overloading of {@code Arrays.hashCode(e)} if e is an array of a
* primitive type, or by calling {@code Arrays.deepHashCode(e)} recursively if e is
* an array of a reference type. The value returned by this method is the
* same value as the method {@code Arrays.asList(array).hashCode()}. If the array is
* {@code null}, the return value is 0.
*
* @param array
* the array whose hash code to compute.
* @return the hash code for {@code array}.
*/
public static int deepHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hashCode = 1;
for (Object element : array) {
int elementHashCode = deepHashCodeElement(element);
hashCode = 31 * hashCode + elementHashCode;
}
return hashCode;
}
private static int deepHashCodeElement(Object element) {
Class> cl;
if (element == null) {
return 0;
}
cl = element.getClass().getComponentType();
if (cl == null) {
return element.hashCode();
}
/*
* element is an array
*/
if (!cl.isPrimitive()) {
return deepHashCode((Object[]) element);
}
if (cl.equals(int.class)) {
return hashCode((int[]) element);
}
if (cl.equals(char.class)) {
return hashCode((char[]) element);
}
if (cl.equals(boolean.class)) {
return hashCode((boolean[]) element);
}
if (cl.equals(byte.class)) {
return hashCode((byte[]) element);
}
if (cl.equals(long.class)) {
return hashCode((long[]) element);
}
if (cl.equals(float.class)) {
return hashCode((float[]) element);
}
if (cl.equals(double.class)) {
return hashCode((double[]) element);
}
return hashCode((short[]) element);
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code byte} array.
* @param array2
* the second {@code byte} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(byte[] array1, byte[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code short} array.
* @param array2
* the second {@code short} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(short[] array1, short[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code char} array.
* @param array2
* the second {@code char} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(char[] array1, char[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code int} array.
* @param array2
* the second {@code int} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(int[] array1, int[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code long} array.
* @param array2
* the second {@code long} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(long[] array1, long[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays. The values are compared in the same manner as
* {@code Float.equals()}.
*
* @param array1
* the first {@code float} array.
* @param array2
* the second {@code float} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
* @see Float#equals(Object)
*/
public static boolean equals(float[] array1, float[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (Float.floatToIntBits(array1[i]) != Float
.floatToIntBits(array2[i])) {
return false;
}
}
return true;
}
/**
* Compares the two arrays. The values are compared in the same manner as
* {@code Double.equals()}.
*
* @param array1
* the first {@code double} array.
* @param array2
* the second {@code double} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
* @see Double#equals(Object)
*/
public static boolean equals(double[] array1, double[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (Double.doubleToLongBits(array1[i]) != Double
.doubleToLongBits(array2[i])) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code boolean} array.
* @param array2
* the second {@code boolean} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal, {@code false} otherwise.
*/
public static boolean equals(boolean[] array1, boolean[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
return false;
}
}
return true;
}
/**
* Compares the two arrays.
*
* @param array1
* the first {@code Object} array.
* @param array2
* the second {@code Object} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal according to {@code equals()}, {@code false} otherwise.
*/
public static boolean equals(Object[] array1, Object[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
Object e1 = array1[i], e2 = array2[i];
if (!(e1 == null ? e2 == null : e1.equals(e2))) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the two given arrays are deeply equal to one another.
* Unlike the method {@code equals(Object[] array1, Object[] array2)}, this method
* is appropriate for use for nested arrays of arbitrary depth.
*
* Two array references are considered deeply equal if they are both {@code null},
* or if they refer to arrays that have the same length and the elements at
* each index in the two arrays are equal.
*
* Two {@code null} elements {@code element1} and {@code element2} are possibly deeply equal if any
* of the following conditions satisfied:
*
* {@code element1} and {@code element2} are both arrays of object reference types, and
* {@code Arrays.deepEquals(element1, element2)} would return {@code true}.
*
* {@code element1} and {@code element2} are arrays of the same primitive type, and the
* appropriate overloading of {@code Arrays.equals(element1, element2)} would return
* {@code true}.
*
* {@code element1 == element2}
*
* {@code element1.equals(element2)} would return {@code true}.
*
* Note that this definition permits {@code null} elements at any depth.
*
* If either of the given arrays contain themselves as elements, the
* behavior of this method is uncertain.
*
* @param array1
* the first {@code Object} array.
* @param array2
* the second {@code Object} array.
* @return {@code true} if both arrays are {@code null} or if the arrays have the
* same length and the elements at each index in the two arrays are
* equal according to {@code equals()}, {@code false} otherwise.
*/
public static boolean deepEquals(Object[] array1, Object[] array2) {
if (array1 == array2) {
return true;
}
if (array1 == null || array2 == null || array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; i++) {
Object e1 = array1[i], e2 = array2[i];
if (!deepEqualsElements(e1, e2)) {
return false;
}
}
return true;
}
private static boolean deepEqualsElements(Object e1, Object e2) {
Class> cl1, cl2;
if (e1 == e2) {
return true;
}
if (e1 == null || e2 == null) {
return false;
}
cl1 = e1.getClass().getComponentType();
cl2 = e2.getClass().getComponentType();
if (cl1 != cl2) {
return false;
}
if (cl1 == null) {
return e1.equals(e2);
}
/*
* compare as arrays
*/
if (!cl1.isPrimitive()) {
return deepEquals((Object[]) e1, (Object[]) e2);
}
if (cl1.equals(int.class)) {
return equals((int[]) e1, (int[]) e2);
}
if (cl1.equals(char.class)) {
return equals((char[]) e1, (char[]) e2);
}
if (cl1.equals(boolean.class)) {
return equals((boolean[]) e1, (boolean[]) e2);
}
if (cl1.equals(byte.class)) {
return equals((byte[]) e1, (byte[]) e2);
}
if (cl1.equals(long.class)) {
return equals((long[]) e1, (long[]) e2);
}
if (cl1.equals(float.class)) {
return equals((float[]) e1, (float[]) e2);
}
if (cl1.equals(double.class)) {
return equals((double[]) e1, (double[]) e2);
}
return equals((short[]) e1, (short[]) e2);
}
/**
* Sorts the specified range in the array in ascending numerical order.
*
* @param array
* the {@code byte} array to be sorted.
* @param start
* the start index to sort.
* @param end
* the last + 1 index to sort.
* @throws IllegalArgumentException
* if {@code start > end}.
* @throws ArrayIndexOutOfBoundsException
* if {@code start < 0} or {@code end > array.length}.
*/
/**
* Creates a {@code String} representation of the {@code boolean[]} passed.
* The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
* {@link String#valueOf(boolean)} and separated by {@code ", "}.
* If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code boolean} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(boolean[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code byte[]} passed. The
* result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(int)} and
* separated by {@code ", "}. If the array is {@code null}, then
* {@code "null"} is returned.
*
* @param array
* the {@code byte} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(byte[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code char[]} passed. The
* result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(char)} and
* separated by {@code ", "}. If the array is {@code null}, then
* {@code "null"} is returned.
*
* @param array
* the {@code char} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(char[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 3);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code double[]} passed.
* The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
* {@link String#valueOf(double)} and separated by {@code ", "}.
* If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code double} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(double[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code float[]} passed.
* The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
* {@link String#valueOf(float)} and separated by {@code ", "}.
* If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code float} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(float[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code int[]} passed. The
* result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(int)} and
* separated by {@code ", "}. If the array is {@code null}, then
* {@code "null"} is returned.
*
* @param array
* the {@code int} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(int[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code long[]} passed. The
* result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(long)} and
* separated by {@code ", "}. If the array is {@code null}, then
* {@code "null"} is returned.
*
* @param array
* the {@code long} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(long[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code short[]} passed.
* The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
* {@link String#valueOf(int)} and separated by {@code ", "}. If
* the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code short} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(short[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a {@code String} representation of the {@code Object[]} passed.
* The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
* {@link String#valueOf(Object)} and separated by {@code ", "}.
* If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code Object} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String toString(Object[] array) {
if (array == null) {
return "null";
}
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(", ");
sb.append(array[i]);
}
sb.append(']');
return sb.toString();
}
/**
* Creates a "deep" {@code String} representation of the
* {@code Object[]} passed, such that if the array contains other arrays,
* the {@code String} representation of those arrays is generated as well.
*
* If any of the elements are primitive arrays, the generation is delegated
* to the other {@code toString} methods in this class. If any element
* contains a reference to the original array, then it will be represented
* as {@code "[...]"}. If an element is an {@code Object[]}, then its
* representation is generated by a recursive call to this method. All other
* elements are converted via the {@link String#valueOf(Object)} method.
*
* @param array
* the {@code Object} array to convert.
* @return the {@code String} representation of {@code array}.
* @since 1.5
*/
public static String deepToString(Object[] array) {
// Special case null to prevent NPE
if (array == null) {
return "null";
}
// delegate this to the recursive method
StringBuilder buf = new StringBuilder(array.length * 9);
deepToStringImpl(array, new Object[] { array }, buf);
return buf.toString();
}
/**
* Implementation method used by {@link #deepToString(Object[])}.
*
* @param array
* the {@code Object[]} to dive into.
* @param origArrays
* the original {@code Object[]}; used to test for self
* references.
* @param sb
* the {@code StringBuilder} instance to append to or
* {@code null} one hasn't been created yet.
* @return the result.
* @see #deepToString(Object[])
*/
private static void deepToStringImpl(Object[] array, Object[] origArrays,
StringBuilder sb) {
if (array == null) {
sb.append("null");
return;
}
sb.append('[');
for (int i = 0; i < array.length; i++) {
if (i != 0) {
sb.append(", ");
}
// establish current element
Object elem = array[i];
if (elem == null) {
// element is null
sb.append("null");
} else {
// get the Class of the current element
Class> elemClass = elem.getClass();
if (elemClass.isArray()) {
// element is an array type
// get the declared Class of the array (element)
Class> elemElemClass = elemClass.getComponentType();
if (elemElemClass.isPrimitive()) {
// element is a primitive array
if (boolean.class.equals(elemElemClass)) {
sb.append(toString((boolean[]) elem));
} else if (byte.class.equals(elemElemClass)) {
sb.append(toString((byte[]) elem));
} else if (char.class.equals(elemElemClass)) {
sb.append(toString((char[]) elem));
} else if (double.class.equals(elemElemClass)) {
sb.append(toString((double[]) elem));
} else if (float.class.equals(elemElemClass)) {
sb.append(toString((float[]) elem));
} else if (int.class.equals(elemElemClass)) {
sb.append(toString((int[]) elem));
} else if (long.class.equals(elemElemClass)) {
sb.append(toString((long[]) elem));
} else if (short.class.equals(elemElemClass)) {
sb.append(toString((short[]) elem));
} else {
// no other possible primitives, so we assert that
throw new AssertionError();
}
} else {
// element is an Object[], so we assert that
assert elem instanceof Object[];
if (deepToStringImplContains(origArrays, elem)) {
sb.append("[...]");
} else {
Object[] newArray = (Object[]) elem;
Object[] newOrigArrays = new Object[origArrays.length + 1];
System.arraycopy(origArrays, 0, newOrigArrays, 0,
origArrays.length);
newOrigArrays[origArrays.length] = newArray;
// make the recursive call to this method
deepToStringImpl(newArray, newOrigArrays, sb);
}
}
} else { // element is NOT an array, just an Object
sb.append(array[i]);
}
}
}
sb.append(']');
}
/**
* Utility method used to assist the implementation of
* {@link #deepToString(Object[])}.
*
* @param origArrays
* An array of Object[] references.
* @param array
* An Object[] reference to look for in {@code origArrays}.
* @return A value of {@code true} if {@code array} is an
* element in {@code origArrays}.
*/
private static boolean deepToStringImplContains(Object[] origArrays,
Object array) {
if (origArrays == null || origArrays.length == 0) {
return false;
}
for (Object element : origArrays) {
if (element == array) {
return true;
}
}
return false;
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code false}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static boolean[] copyOf(boolean[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code (byte) 0}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static byte[] copyOf(byte[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code '\\u0000'}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static char[] copyOf(char[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code 0.0d}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static double[] copyOf(double[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code 0.0f}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static float[] copyOf(float[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code 0}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static int[] copyOf(int[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code 0L}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static long[] copyOf(long[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code (short) 0}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static short[] copyOf(short[] original, int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code null}.
*
* @param original the original array
* @param newLength the length of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static T[] copyOf(T[] original, int newLength) {
if (original == null) {
throw new NullPointerException();
}
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength);
}
/**
* Copies {@code newLength} elements from {@code original} into a new array.
* If {@code newLength} is greater than {@code original.length}, the result is padded
* with the value {@code null}.
*
* @param original the original array
* @param newLength the length of the new array
* @param newType the class of the new array
* @return the new array
* @throws NegativeArraySizeException if {@code newLength < 0}
* @throws NullPointerException if {@code original == null}
* @throws ArrayStoreException if a value in {@code original} is incompatible with T
* @since 1.6
*/
public static T[] copyOf(U[] original, int newLength, Class extends T[]> newType) {
// We use the null pointer check in copyOfRange for exception priority compatibility.
if (newLength < 0) {
throw new NegativeArraySizeException();
}
return copyOfRange(original, 0, newLength, newType);
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code false}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static boolean[] copyOfRange(boolean[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
boolean[] result = new boolean[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code (byte) 0}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static byte[] copyOfRange(byte[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
byte[] result = new byte[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code '\\u0000'}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static char[] copyOfRange(char[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
char[] result = new char[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code 0.0d}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static double[] copyOfRange(double[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
double[] result = new double[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code 0.0f}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static float[] copyOfRange(float[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
float[] result = new float[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code 0}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static int[] copyOfRange(int[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
int[] result = new int[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code 0L}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static long[] copyOfRange(long[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
long[] result = new long[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code (short) 0}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
public static short[] copyOfRange(short[] original, int start, int end) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
short[] result = new short[resultLength];
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code null}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @since 1.6
*/
@SuppressWarnings("unchecked")
public static T[] copyOfRange(T[] original, int start, int end) {
int originalLength = original.length; // For exception priority compatibility.
if (start > end) {
throw new IllegalArgumentException();
}
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
T[] result = (T[]) Array.newInstance(original.getClass().getComponentType(), resultLength);
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Copies elements from {@code original} into a new array, from indexes start (inclusive) to
* end (exclusive). The original order of elements is preserved.
* If {@code end} is greater than {@code original.length}, the result is padded
* with the value {@code null}.
*
* @param original the original array
* @param start the start index, inclusive
* @param end the end index, exclusive
* @return the new array
* @throws ArrayIndexOutOfBoundsException if {@code start < 0 || start > original.length}
* @throws IllegalArgumentException if {@code start > end}
* @throws NullPointerException if {@code original == null}
* @throws ArrayStoreException if a value in {@code original} is incompatible with T
* @since 1.6
*/
@SuppressWarnings("unchecked")
public static T[] copyOfRange(U[] original, int start, int end, Class extends T[]> newType) {
if (start > end) {
throw new IllegalArgumentException();
}
int originalLength = original.length;
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
int resultLength = end - start;
int copyLength = Math.min(resultLength, originalLength - start);
T[] result = (T[]) Array.newInstance(newType.getComponentType(), resultLength);
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
}
================================================
FILE: orm-library/src/main/java/net/tsz/afinal/core/AsyncTask.java
================================================
package net.tsz.afinal.core;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 拷贝 https://android.googlesource.com/platform/frameworks/base/+/jb-release/
* core/java/android/os/AsyncTask.java
* 修改了线程池属性,让并发线程按顺序执行
* @author michael
*
* @param
* @param