AlgART Home

net.algart.arrays
Class Arrays

java.lang.Object
  extended by net.algart.arrays.Arrays

public class Arrays
extends java.lang.Object

A set of static methods useful for working with AlgART arrays.

This class cannot be instantiated.

AlgART Laboratory 2007-2013

Since:
JDK 1.5
Version:
1.2
Author:
Daniel Alievsky

Nested Class Summary
Modifier and Type Class and Description
static class Arrays.ComparingCopyStatus
          The information about the copying, returned by compareAndCopy(ArrayContext, UpdatableArray, Array) and Matrices.compareAndCopy(ArrayContext, Matrix, Matrix) methods.
static class Arrays.Copier
          Implementation of Arrays.ParallelExecutor performing simple copying of the source array.
static class Arrays.CopyAlgorithm
          The information about the internal algorithm, which was used by copying methods of this package: copy(ArrayContext, UpdatableArray, Array), copy(ArrayContext, UpdatableArray, Array, int, boolean), compareAndCopy(ArrayContext, UpdatableArray, Array), Matrices.copy(ArrayContext, Matrix, Matrix), etc.
static class Arrays.CopyStatus
          The information about the copying, returned by copying methods of this package: copy(ArrayContext, UpdatableArray, Array), copy(ArrayContext, UpdatableArray, Array, int, boolean), Matrices.copy(ArrayContext, Matrix, Matrix), etc.
static class Arrays.MinMaxInfo
          The helper class for rangeOf(PArray, MinMaxInfo) method, containing information about the minimum and maximum in some AlgART array.
static class Arrays.ParallelExecutor
          The class simplifying the parallel processing a large AlgART array in several threads, where each thread process a set of ranges of the source array (Array.subArray).
static class Arrays.SystemSettings
          A set of static methods for getting some important global settings, stored in system properties and used for customizing modules processing AlgART arrays.
static class Arrays.TaskExecutionOrder
          Describes when to execute the task passed to addShutdownTask(Runnable, TaskExecutionOrder) method.
 
Field Summary
Modifier and Type Field and Description
static int BITS_PER_BIT
          The number of bits per every element of bit array: 1.
static int BITS_PER_BYTE
          The number of bits per every element of byte array: 8.
static int BITS_PER_CHAR
          The number of bits per every element of character array: 16.
static int BITS_PER_DOUBLE
          The number of bits per every element of double array: 64.
static int BITS_PER_FLOAT
          The number of bits per every element of float array: 32.
static int BITS_PER_INT
          The number of bits per every element of int array: 32.
static int BITS_PER_LONG
          The number of bits per every element of long array: 64.
static int BITS_PER_SHORT
          The number of bits per every element of short array: 16.
static SimpleMemoryModel SMM
          Contains SimpleMemoryModel.getInstance().
 
Method Summary
Modifier and Type Method and Description
static void addShutdownTask(java.lang.Runnable task, Arrays.TaskExecutionOrder whenToExecute)
          Schedules the given task to be performed while system shutting down.
static void applyFunc(ArrayContext context, boolean truncateOverflows, Func f, UpdatablePArray result, PArray... x)
          Equivalent to applyFunc(context, f, truncateOverflows, 0, true, result, x).
static void applyFunc(ArrayContext context, boolean truncateOverflows, int numberOfTasks, boolean strictMode, Func f, UpdatablePArray result, PArray... x)
          Creates a "lazy" array by lazy = asFuncArray(truncateOverflows, f, result.type(), x) call and copies it into the result argument by copy(context, result, lazy, numberOfTasks, strictMode) call.
static void applyFunc(ArrayContext context, Func f, UpdatablePArray result, PArray... x)
          Equivalent to applyFunc(context, f, true, result, x).
static java.lang.CharSequence asCharSequence(CharArray charArray)
          Returns a view of the character array implementing standard CharSequence interface.
static Array asConcatenation(Array... arrays)
          Returns an immutable view of the passed sequence of AlgART arrays as their concatenation.
static
<T extends PArray>
T
asFuncArray(boolean truncateOverflows, Func f, java.lang.Class<? extends T> requiredType, PArray... x)
          Returns an immutable view of the passed x AlgART arrays (with primitive element type), where each element #k is a result of calling f.get(x[0].getDouble(k), x[1].getDouble(k), ...), i.e. the result of the passed function for arguments, equal to the corresponding elements #k in all passed arrays.
static
<T extends PArray>
T
asFuncArray(Func f, java.lang.Class<? extends T> requiredType, PArray... x)
          Equivalent to asFuncArray(true, f, requiredType, x).
static
<T extends PArray>
T
asIndexFuncArray(boolean truncateOverflows, Func f, java.lang.Class<? extends T> requiredType, long length)
          An analog of the asFuncArray(boolean, Func, Class, PArray...) method, where the passed function is applied not to the elements of some source array, but to the index of the resulting array.
static
<T extends PArray>
T
asIndexFuncArray(Func f, java.lang.Class<? extends T> requiredType, long length)
          Equivalent to asIndexFuncArray(true, f, requiredType, length).
static
<E> java.util.List<E>
asList(Array array, java.lang.Class<E> listElementType)
          Returns a list backed by the specified array.
static
<E> java.util.List<E>
asList(ObjectArray<E> array)
          Equivalent to asList(array, array.elementType()}.
static Array asShifted(Array array, long shift)
          Returns an immutable view of the passed AlgART array, cyclically shifted to the right by the specified number of elements.
static
<T extends UpdatablePArray>
T
asUpdatableFuncArray(boolean truncateOverflows, Func.Updatable f, java.lang.Class<? extends T> requiredType, UpdatablePArray... x)
          An extended analog of the asFuncArray(boolean, Func, Class, PArray...) method allowing to create updatable view of the source array.
static
<T extends UpdatablePArray>
T
asUpdatableFuncArray(Func.Updatable f, java.lang.Class<? extends T> requiredType, UpdatablePArray... x)
          Equivalent to asUpdatableFuncArray(true, f, requiredType, x).
static long bitsPerElement(java.lang.Class<?> elementType)
          Returns the size in bits, required for each element of an array with the given primitive element type.
static long cardinality(ArrayContext context, BitArray bitArray)
          Returns the number of bits set to true in this array.
static long cardinality(BitArray bitArray)
          Returns the number of bits set to true in this array.
static long compactCyclicPositions(long length, long[] positions)
          Finds the shortest cyclic range, containing all passed positions in the cyclic range 0..length-1, returns the beginning of this range as the method result, cyclically subtracts it from all elements of the passed array and returns the sorted array of resulting positions in the positions argument.
static Arrays.ComparingCopyStatus compareAndCopy(ArrayContext context, UpdatableArray dest, Array src)
          This method is an analog of copy(ArrayContext, UpdatableArray, Array) allowing to know, whether the destination array was really modified while copying.
static Arrays.CopyStatus copy(ArrayContext context, UpdatableArray dest, Array src)
          Copies min(dest.length(), src.length()) elements of src array, starting from index 0, to dest array, starting from index 0.
static Arrays.CopyStatus copy(ArrayContext context, UpdatableArray dest, Array src, int numberOfTasks)
          This method is an analog of copy(ArrayContext, UpdatableArray, Array), allowing to specify the number of parallel tasks.
static Arrays.CopyStatus copy(ArrayContext context, UpdatableArray dest, Array src, int numberOfTasks, boolean strictMode)
          This method is an analog of copy(ArrayContext, UpdatableArray, Array) and copy(ArrayContext, UpdatableArray, Array, int) providing a special "non-strict" copying mode.
static java.lang.Class<?> elementType(java.lang.Class<? extends PArray> arrayType)
          Returns the type of elements corresponding to the passed class of primitive arrays.
static void freeAllResources()
          Releases all resources, associated with any AlgART arrays created by this package.
static boolean gcAndAwaitFinalization(int timeoutInMilliseconds)
          Performs a loop of System.runFinalization() and System.gc(), and waits for finishing all finalization tasks that are scheduled by any classes of this package.
static Func getFunc(Array array)
          Returns the mathematical function, used for creating the passed functional array, or throws an exception if this array is not functional.
static long[] getIndexDimensions(Array array)
          Returns the dimensions of the matrix, coordinates of which are used as arguments of the underlying function in the passed index-based functional array, or throws an exception if this array is not a functional array, calculated on the base of indexes.
static long getShift(Array array)
          Returns the shift, used for creating the passed shited array, or throws an exception if this array is not shifted.
static ThreadPoolFactory getThreadPoolFactory(ArrayContext context)
          Returns context.getThreadPoolFactory() if context!=null or DefaultThreadPoolFactory.getDefaultThreadPoolFactory() if context==null.
static boolean getTruncationMode(Array array)
          Returns the value of truncateOverflows argument of asFuncArray(boolean, Func, Class, PArray...) method (or one of its overloaded versions), used for creating the passed functional array, or throws an exception if this array is not functional.
static Array[] getUnderlyingArrays(Array array)
          Returns Java array of the underlying AlgART arrays of the given AlgART array.
static int getUnderlyingArraysCount(Array array)
          Returns the number of the underlying AlgART arrays of the given AlgART array.
static boolean[] getUnderlyingArraysNewStatus(Array array)
          Returns boolean[] array, containing underlyingArrays[k].isNew() values, for all underlying arrays of the passed one.
static int goodStartOffsetInArrayOfLongs(BitArray bitArray, long position, int maxAvailableGap)
          Returns the minimal offset=0..maxAvailableGap-1, for which the calls getBits(position, destArray, offset, someCount) and (for updatable array) setBits(position, srcArray, offset, someCount) work essentially faster than for most of other ("slow") positions, or 0 if there is no such offset, in particular, if position>=length().
static boolean histogramOf(ArrayContext context, PArray array, long[] histogram, double from, double to)
          Increments the histogram of frequency of values in the passed array.
static boolean histogramOf(PArray array, long[] histogram, double from, double to)
          Equivalent to histogramOf(null, array, histogram, from, to).
static void insertBit(MutableBitArray array, long index, boolean value)
          Inserts the specified boolean value at the specified position in the bit array.
static void insertChar(MutableCharArray array, long index, char value)
          Inserts the specified char value at the specified position in the char array.
static void insertDouble(MutablePFloatingArray array, long index, double value)
          Inserts the specified double value at the specified position in the double array.
static void insertEmptyRange(MutableArray array, long position, long count)
          Increase the array length by count and shifts all elements starting from position to the right (adds count to their indexes).
static void insertInt(MutablePIntegerArray array, long index, int value)
          Inserts the specified int value at the specified position in the int array.
static void insertLong(MutablePIntegerArray array, long index, long value)
          Inserts the specified long value at the specified position in the long array.
static
<E> void
insertObject(MutableObjectArray<E> array, long index, E value)
          Inserts the specified Object value at the specified position in the object array.
static boolean isBitType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is BitArray.class, UpdatableBitArray.class or MutableBitArray.class (but not some of their subinterfaces or subclasses).
static boolean isByteType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is ByteArray.class, UpdatableByteArray.class or MutableByteArray.class (but not some of their subinterfaces or subclasses).
static boolean isCharType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is CharArray.class, UpdatableCharArray.class or MutableCharArray.class (but not some of their subinterfaces or subclasses).
static boolean isConcatenation(Array array)
          Returns true if the passed array is a concatenation view, i.e. is a result of asConcatenation(Array...) method.
static boolean isDoubleType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is DoubleArray.class, UpdatableDoubleArray.class or MutableDoubleArray.class (but not some of their subinterfaces or subclasses).
static boolean isFloatType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is FloatArray.class, UpdatableFloatArray.class or MutableFloatArray.class (but not some of their subinterfaces or subclasses).
static boolean isFuncArray(Array array)
          Returns true if the passed array is not null functional array, created by this package.
static boolean isIndexFuncArray(Array array)
          Returns true if the passed array is not null functional array, created by this package, calculated on the base of array indexes only, not depending on another arrays/matrices.
static boolean isIntType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is IntArray.class, UpdatableIntArray.class or MutableIntArray.class (but not some of their subinterfaces or subclasses).
static boolean isLongType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is LongArray.class, UpdatableLongArray.class or MutableLongArray.class (but not some of their subinterfaces or subclasses).
static boolean isNCopies(Array array)
          Returns true if the passed array is not null and was created by one of nXxxCopies methods of this class and, so, all array elements have the same constant value.
static boolean isObjectType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is ObjectArray.class, UpdatableObjectArray.class or MutableObjectArray.class (but not some of their subinterfaces or subclasses).
static boolean isShifted(Array array)
          Returns true if the passed array is not null shifted array, i.e. is a result of asShifted(Array, long) method.
static boolean isShortType(java.lang.Class<? extends Array> arrayType)
          Return true if and only if the passed class is ShortArray.class, UpdatableShortArray.class or MutableShortArray.class (but not some of their subinterfaces or subclasses).
static void lengthUnsigned(MutableArray array, long newUnsignedLength)
          Equivalent to MutableArray.length(long) method with the only exception that newUnsignedLength is considered as unsigned long value.
static long longMul(long... multipliers)
          Returns the product of all passed multipliers (multipliers[0]*multipliers[1]*...), if it is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow").
static long longMul(long[] multipliers, int from, int to)
          Returns the product of passed multipliers from the index, specified in from argument (inclusive), until the index, specified in to argument (exclusive), i.e. multipliers[from]*multipliers[from+1]*...*multipliers[to-1], if this product is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow").
static long longMul(long a, long b)
          Returns the product a*b, if it is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow").
static long maxPossibleIntegerValue(java.lang.Class<? extends PFixedArray> arrayType)
          Returns the maximal possible value, that can be stored in elements of the fixed-point primitive array (byte and short elements are interpreted as unsigned).
static double maxPossibleValue(java.lang.Class<? extends Array> arrayType, double valueForFloatingPoint)
          If arrayType is BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces, this method is equivalent to (double)maxPossibleIntegerValue(arrayType); if arrayType is FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces, returns valueForFloatingPoint.
static long minPossibleIntegerValue(java.lang.Class<? extends PFixedArray> arrayType)
          Returns the minimal possible value, that can be stored in elements of the fixed-point primitive array (byte and short elements are interpreted as unsigned).
static double minPossibleValue(java.lang.Class<? extends Array> arrayType, double valueForFloatingPoint)
          If arrayType is BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces, this method is equivalent to (double)minPossibleIntegerValue(arrayType); if arrayType is FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces, returns valueForFloatingPoint.
static BitArray nBitCopies(long n, boolean element)
          Constructs an immutable unresizable bit array consisting of n copies of the specified element.
static ByteArray nByteCopies(long n, byte element)
          Constructs an immutable unresizable byte array consisting of n copies of the specified element.
static CharArray nCharCopies(long n, char element)
          Constructs an immutable unresizable char array consisting of n copies of the specified element.
static DoubleArray nDoubleCopies(long n, double element)
          Constructs an immutable unresizable double array consisting of n copies of the specified element.
static FloatArray nFloatCopies(long n, float element)
          Constructs an immutable unresizable float array consisting of n copies of the specified element.
static IntArray nIntCopies(long n, int element)
          Constructs an immutable unresizable int array consisting of n copies of the specified element.
static LongArray nLongCopies(long n, long element)
          Constructs an immutable unresizable long array consisting of n copies of the specified element.
static
<T> ObjectArray<T>
nNullCopies(long n, java.lang.Class<T> elementType)
          The version of nObjectCopies(n, element) method with element=null that allows to specify the element type of the returned array.
static
<T> ObjectArray<T>
nObjectCopies(long n, T element)
          Constructs an immutable unresizable Object array consisting of n copies of the specified element.
static ArrayComparator normalOrderComparator(UpdatableArray array)
          Returns comparator allowing to sort the array in normal (increasing) order via sort method.
static PArray nPCopies(long n, java.lang.Class<?> elementType, double element)
          Constructs an immutable unresizable array consisting of n copies of the specified double element, cast to the specified element type.
static PFixedArray nPFixedCopies(long n, java.lang.Class<?> elementType, long element)
          Constructs an immutable unresizable array consisting of n copies of the specified integer element, cast to the specified element type.
static ShortArray nShortCopies(long n, short element)
          Constructs an immutable unresizable short array consisting of n copies of the specified element.
static void packBitsGreater(ArrayContext context, UpdatableBitArray bits, PArray array, double threshold)
          Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) >= threshold.
static void packBitsGreater(UpdatableBitArray bits, PArray array, double threshold)
          Equivalent to packBitsGreater(null, bits, array, threshold).
static void packBitsGreaterOrEqual(ArrayContext context, UpdatableBitArray bits, PArray array, double threshold)
          Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) >= threshold.
static void packBitsGreaterOrEqual(UpdatableBitArray bits, PArray array, double threshold)
          Equivalent to packBitsGreaterOrEqual(null, bits, array, threshold).
static void packBitsLess(ArrayContext context, UpdatableBitArray bits, PArray array, double threshold)
          Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) <= threshold.
static void packBitsLess(UpdatableBitArray bits, PArray array, double threshold)
          Equivalent to packBitsLess(null, bits, array, threshold).
static void packBitsLessOrEqual(ArrayContext context, UpdatableBitArray bits, PArray array, double threshold)
          Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) <= threshold.
static void packBitsLessOrEqual(UpdatableBitArray bits, PArray array, double threshold)
          Equivalent to packBitsLessOrEqual(null, bits, array, threshold).
static long preciseSumOf(ArrayContext context, PFixedArray array)
          Equivalent to preciseSumOf(context, array, false).
static long preciseSumOf(ArrayContext context, PFixedArray array, boolean checkOverflow)
          Returns the integer sum of all array elements: the results of array.getLong(k) for all k==0,1,...,array.length()-1.
static long preciseSumOf(PFixedArray array)
          Equivalent to preciseSumOf(null, array, false).
static long preciseSumOf(PFixedArray array, boolean checkOverflow)
          Equivalent to preciseSumOf(null, array, checkOverflow).
static Range rangeOf(ArrayContext context, PArray array)
          Equivalent to rangeOf(context, array, null).
static Range rangeOf(ArrayContext context, PArray array, Arrays.MinMaxInfo minMaxInfo)
          Returns a Range.valueOf(min, max), where min is equal to the minimal array element and min is equal to the maximal array element.
static Range rangeOf(PArray array)
          Equivalent to rangeOf(null, array, null).
static Range rangeOf(PArray array, Arrays.MinMaxInfo minMaxInfo)
          Equivalent to rangeOf(null, array, minMaxInfo).
static void read(java.io.InputStream inputStream, UpdatablePArray array, java.nio.ByteOrder byteOrder)
          Reads all elements of the passed array from the passed input stream from its current position.
static void remove(MutableArray array, long position)
          Removes 1 element at the specified position in the array.
static void removeRange(MutableArray array, long position, long count)
          Removes all elements at positions position..position+count-1 in the array.
static ArrayComparator reverseOrderComparator(UpdatableArray array)
          Returns comparator allowing to sort the array in reverse (decreasing) order via sort method.
static long sizeOf(Array array)
          Estimates the size in bytes of the array.
static double sizeOf(java.lang.Class<?> elementType)
          Returns the size in bytes, required for each element of an array with the given primitive element type.
static long sizeOf(java.lang.Class<?> elementType, long arrayLength)
          Estimates the size in bytes of the array with the given primitive element type and the given length.
static void sort(UpdatableArray array, ArrayComparator comparator)
          Sorts the array in increasing order, according to passed comparator.
static double sumOf(ArrayContext context, PArray array)
          Returns the sum of all array elements: the results of array.getDouble(k) for all k==0,1,...,array.length()-1.
static double sumOf(PArray array)
          Equivalent to sumOf(null, array).
static
<T extends java.lang.Exception>
void
throwException(java.lang.Class<? extends T> exceptionClass, java.lang.Throwable exception)
          Throws the specified exception, supposed to be unchecked or belonging to the specified class — in other words, throws the argument, if it is RuntimeException, Error or an instance of exceptionClass.
static void throwUncheckedException(java.lang.Throwable exception)
          Throws the specified unchecked exception — in other words, throws the argument, if it is RuntimeException or Error.
static java.lang.String toHexString(Array array, java.lang.String separator, int maxStringLength)
          Joins and returns as a string the "hexadecimal" string representations for all elements of the AlgART array, separating elements by the given separator.
static java.lang.Object toJavaArray(Array array)
          Returns a Java array containing all of the elements in this AlgART array in proper sequence, if the length of this array is not too high (not greater than Integer.MAX_VALUE).
static boolean[] toJavaArray(BitArray array)
          Equivalent to (boolean[])toJavaArray((Array)array).
static byte[] toJavaArray(ByteArray array)
          Equivalent to (byte[])toJavaArray((Array)array).
static char[] toJavaArray(CharArray array)
          Equivalent to (char[])toJavaArray((Array)array).
static double[] toJavaArray(DoubleArray array)
          Equivalent to (double[])toJavaArray((Array)array).
static float[] toJavaArray(FloatArray array)
          Equivalent to (float[])toJavaArray((Array)array).
static int[] toJavaArray(IntArray array)
          Equivalent to (int[])toJavaArray((Array)array).
static long[] toJavaArray(LongArray array)
          Equivalent to (long[])toJavaArray((Array)array).
static
<E> E[]
toJavaArray(ObjectArray<E> array)
          Equivalent to (E[])toJavaArray((Array)array).
static short[] toJavaArray(ShortArray array)
          Equivalent to (short[])toJavaArray((Array)array).
static java.lang.String toString(Array array, java.util.Locale locale, java.lang.String format, java.lang.String separator, int maxStringLength)
          Joins and returns as a string the string representations for all elements of the AlgART array, separating elements by the given separator, using format string for formatting numeric elements.
static java.lang.String toString(Array array, java.lang.String separator, int maxStringLength)
          Joins and returns as a string the standard string representations for all elements of the AlgART array, separating elements by the given separator.
static java.lang.String toString(CharArray charArray)
          Returns a string containing all characters in this character array (in the same order as in this array).
static
<T extends Array>
java.lang.Class<T>
type(java.lang.Class<T> arraySupertype, java.lang.Class<?> elementType)
          Returns the type of immutable, unresizable or resizable arrays, which is a subtype of (or same type as) arraySupertype and corresponds to the passed element type.
static void unpackBits(ArrayContext context, UpdatablePArray array, BitArray bits, double filler0, double filler1)
          Sets every element #k of the passed updatable array to filler0 value, if the corresponding element #k of bits array is false (0), or to filler1, if this bit is true (1).
static void unpackBits(UpdatablePArray array, BitArray bits, double filler0, double filler1)
          Equivalent to unpackBits(null, array, bits, filler0, filler1).
static void unpackUnitBits(ArrayContext context, UpdatablePArray array, BitArray bits, double filler1)
          Sets every element #k of the passed updatable array to filler1 value, if the corresponding element #k of bits array is true (1), or doesn't change it, if this bit is false (0).
static void unpackUnitBits(UpdatablePArray array, BitArray bits, double filler1)
          Equivalent to unpackUnitBits(null, array, bits, filler1).
static void unpackZeroBits(ArrayContext context, UpdatablePArray array, BitArray bits, double filler0)
          Sets every element #k of the passed updatable array to filler0 value, if the corresponding element #k of bits array is false (0), or doesn't change it, if this bit is true (1).
static void unpackZeroBits(UpdatablePArray array, BitArray bits, double filler0)
          Equivalent to unpackZeroBits(null, array, bits, filler0).
static void write(java.io.OutputStream outputStream, PArray array, java.nio.ByteOrder byteOrder)
          Writes all elements of the passed array to the passed output stream from its current position.
static void zeroFill(UpdatableArray array)
          Fills all elements of the array by zero (0 for numbers, false for boolean values, null or some "empty" objects for non-primitive elements).
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SMM

public static final SimpleMemoryModel SMM
Contains SimpleMemoryModel.getInstance(). It is just a more compact alternative for the expression "SimpleMemoryModel.getInstance()".


BITS_PER_BIT

public static final int BITS_PER_BIT
The number of bits per every element of bit array: 1. This value is returned by PArray.bitsPerElement() method for instances of BitArray, UpdatableBitArray, MutableBitArray.

See Also:
Constant Field Values

BITS_PER_CHAR

public static final int BITS_PER_CHAR
The number of bits per every element of character array: 16. This value is returned by PArray.bitsPerElement() method for instances of CharArray, UpdatableCharArray, MutableCharArray.

See Also:
Constant Field Values

BITS_PER_BYTE

public static final int BITS_PER_BYTE
The number of bits per every element of byte array: 8. This value is returned by PArray.bitsPerElement() method for instances of ByteArray, UpdatableByteArray, MutableByteArray.

See Also:
Constant Field Values

BITS_PER_SHORT

public static final int BITS_PER_SHORT
The number of bits per every element of short array: 16. This value is returned by PArray.bitsPerElement() method for instances of ShortArray, UpdatableShortArray, MutableShortArray.

See Also:
Constant Field Values

BITS_PER_INT

public static final int BITS_PER_INT
The number of bits per every element of int array: 32. This value is returned by PArray.bitsPerElement() method for instances of IntArray, UpdatableIntArray, MutableIntArray.

See Also:
Constant Field Values

BITS_PER_LONG

public static final int BITS_PER_LONG
The number of bits per every element of long array: 64. This value is returned by PArray.bitsPerElement() method for instances of LongArray, UpdatableLongArray, MutableLongArray.

See Also:
Constant Field Values

BITS_PER_FLOAT

public static final int BITS_PER_FLOAT
The number of bits per every element of float array: 32. This value is returned by PArray.bitsPerElement() method for instances of FloatArray, UpdatableFloatArray, MutableFloatArray.

See Also:
Constant Field Values

BITS_PER_DOUBLE

public static final int BITS_PER_DOUBLE
The number of bits per every element of double array: 64. This value is returned by PArray.bitsPerElement() method for instances of DoubleArray, UpdatableDoubleArray, MutableDoubleArray.

See Also:
Constant Field Values
Method Detail

elementType

public static java.lang.Class<?> elementType(java.lang.Class<? extends PArray> arrayType)
Returns the type of elements corresponding to the passed class of primitive arrays. The passed class must be one of basic interfaces BitArray.class, CharArray.class, ByteArray.class, ShortArray.class, IntArray.class, LongArray.class, FloatArray.class, DoubleArray.class, or their subinterfaces (like UpdatableByteArray.class or MutableIntArray.class), or a class implementing one of these interfaces.

More precisely, this method returns:

Parameters:
arrayType - the type of some primitive array.
Returns:
the corresponding element type.
Throws:
java.lang.NullPointerException - if the passed argument is null.
java.lang.IllegalArgumentException - if the passed argument is not a class of primitive array.
See Also:
Array.elementType()

type

public static <T extends Array> java.lang.Class<T> type(java.lang.Class<T> arraySupertype,
                                                        java.lang.Class<?> elementType)
Returns the type of immutable, unresizable or resizable arrays, which is a subtype of (or same type as) arraySupertype and corresponds to the passed element type.

Namely, if arraySupertype is not UpdatableArray or its inheritor, returns:

If arraySupertype is UpdatableArray or its inheritor, returns:

If arraySupertype is MutableArray or its inheritor, returns:

Parameters:
arraySupertype - required array supertype.
elementType - required element type.
Returns:
the corresponding array type.
Throws:
java.lang.NullPointerException - if one of the passed arguments is null.
java.lang.ClassCastException - if arraySupertype does not allow storing the required element type (for example, it is PArray, but elementType is not a primitive type).

isBitType

public static boolean isBitType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is BitArray.class, UpdatableBitArray.class or MutableBitArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for bit arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART bit arrays.

isCharType

public static boolean isCharType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is CharArray.class, UpdatableCharArray.class or MutableCharArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for character arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART character arrays.

isByteType

public static boolean isByteType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is ByteArray.class, UpdatableByteArray.class or MutableByteArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for byte arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART byte arrays.

isShortType

public static boolean isShortType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is ShortArray.class, UpdatableShortArray.class or MutableShortArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for short arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART short arrays.

isIntType

public static boolean isIntType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is IntArray.class, UpdatableIntArray.class or MutableIntArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for int arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART int arrays.

isLongType

public static boolean isLongType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is LongArray.class, UpdatableLongArray.class or MutableLongArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for long arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART long arrays.

isFloatType

public static boolean isFloatType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is FloatArray.class, UpdatableFloatArray.class or MutableFloatArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for float arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART float arrays.

isDoubleType

public static boolean isDoubleType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is DoubleArray.class, UpdatableDoubleArray.class or MutableDoubleArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for double arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART double arrays.

isObjectType

public static boolean isObjectType(java.lang.Class<? extends Array> arrayType)
Return true if and only if the passed class is ObjectArray.class, UpdatableObjectArray.class or MutableObjectArray.class (but not some of their subinterfaces or subclasses). These 3 classes are named canonical AlgART array types for object arrays: see Array.type(), Array.updatableType(), Array.mutableType() methods. Returns false if the argument is null.

Parameters:
arrayType - the checked array class.
Returns:
whether the checked class is one of 3 canonical types of AlgART object arrays.

sizeOf

public static long sizeOf(Array array)
Estimates the size in bytes of the array.

More precisely:

  1. For BitArray, returns 8*PackedBitArrays.packedLength(array.length()) (8 is the number of bytes in one long value).
  2. For other variants of PArray, returns array.length()*sizeOfElement, where sizeOfElement=((PArray)array).bitsPerElement()/8.
  3. For combined arrays, returns the sum of the results of this method, recursively called for all AlgART arrays contained in the underlying internal storage.
  4. In all other cases, returns -1 ("unknown size"). Also returns -1 in the case #3, if the result of this method for some of arrays in the internal storage is -1.

In a case of calculation overflow, this method returns Long.MAX_VALUE always. (For example, it's possible for an array generated by nDoubleCopies(Long.MAX_VALUE, someFiller) call.)

Parameters:
array - some AlgART array.
Returns:
the estimated size of this array in bytes.
Throws:
java.lang.NullPointerException - if the argument is null.
See Also:
sizeOf(Class, long), sizeOf(Class), Matrices.sizeOf(Matrix)

sizeOf

public static long sizeOf(java.lang.Class<?> elementType,
                          long arrayLength)
Estimates the size in bytes of the array with the given primitive element type and the given length.

More precisely:

There are two exceptions from these rules:

  1. in a case of calculation overflow, this method returns Long.MAX_VALUE always;
  2. in a case of negative argument (arrayLength<0), this method returns -1 always.

This method never throws exceptions.

Parameters:
elementType - some primitive element type; may be null, then −1 is returned.
arrayLength - the desired length of the AlgART array.
Returns:
the estimated size of the AlgART array in bytes or −1 if it is unknown.
See Also:
sizeOf(Array)

sizeOf

public static double sizeOf(java.lang.Class<?> elementType)
Returns the size in bytes, required for each element of an array with the given primitive element type.

More precisely:

Parameters:
elementType - some primitive element type; may be null, then −1 is returned.
Returns:
the size of each element of the AlgART array in bytes or −1 if it is unknown.
See Also:
sizeOf(Array)

bitsPerElement

public static long bitsPerElement(java.lang.Class<?> elementType)
Returns the size in bits, required for each element of an array with the given primitive element type.

More precisely:

Parameters:
elementType - some primitive element type; may be null, then −1 is returned.
Returns:
the size of each element of the AlgART array in bits or −1 if it is unknown.
See Also:
sizeOf(Array), PArray.bitsPerElement()

minPossibleIntegerValue

public static long minPossibleIntegerValue(java.lang.Class<? extends PFixedArray> arrayType)
Returns the minimal possible value, that can be stored in elements of the fixed-point primitive array (byte and short elements are interpreted as unsigned). Namely, returns: In all other cases, this method throws IllegalArgumentException.

Parameters:
arrayType - the type of some fixed-point primitive array.
Returns:
the minimal possible value, that can be stored in such arrays.
Throws:
java.lang.NullPointerException - if the passed argument is null.
java.lang.IllegalArgumentException - if the passed argument is not BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces.
See Also:
PFixedArray.minPossibleValue()

maxPossibleIntegerValue

public static long maxPossibleIntegerValue(java.lang.Class<? extends PFixedArray> arrayType)
Returns the maximal possible value, that can be stored in elements of the fixed-point primitive array (byte and short elements are interpreted as unsigned). Namely, returns: In all other cases, this method throws IllegalArgumentException.

Parameters:
arrayType - the type of some fixed-point primitive array.
Returns:
the maximal possible value, that can be stored in such arrays.
Throws:
java.lang.NullPointerException - if the passed argument is null.
java.lang.IllegalArgumentException - if the passed argument is not BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces.
See Also:
PFixedArray.maxPossibleValue()

minPossibleValue

public static double minPossibleValue(java.lang.Class<? extends Array> arrayType,
                                      double valueForFloatingPoint)
If arrayType is BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces, this method is equivalent to (double)minPossibleIntegerValue(arrayType); if arrayType is FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces, returns valueForFloatingPoint. In all other cases — for example, if the passed class is a common interface as PArray, that can have different minimal elements — this method throws IllegalArgumentException.

Parameters:
arrayType - the type of some AlgART array.
valueForFloatingPoint - the value returned for floating-point or object array type.
Returns:
the minimal possible value, that can be stored in such fixed-point primitive arrays, or valueForFloatingPoint for other array types.
Throws:
java.lang.NullPointerException - if the passed arrayType is null.
java.lang.IllegalArgumentException - if the passed arrayType is not BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces.
See Also:
PArray.minPossibleValue(double)

maxPossibleValue

public static double maxPossibleValue(java.lang.Class<? extends Array> arrayType,
                                      double valueForFloatingPoint)
If arrayType is BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray or an inheritor / implementing class of some of these interfaces, this method is equivalent to (double)maxPossibleIntegerValue(arrayType); if arrayType is FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces, returns valueForFloatingPoint. In all other cases — for example, if the passed class is a common interface as PArray, that can have different maximal elements — this method throws IllegalArgumentException.

Parameters:
arrayType - the type of some AlgART array.
valueForFloatingPoint - the value returned for floating-point or object array type.
Returns:
the maximal possible value, that can be stored in such fixed-point primitive arrays, or valueForFloatingPoint for other array types.
Throws:
java.lang.NullPointerException - if the passed arrayType is null.
java.lang.IllegalArgumentException - if the passed arrayType is not BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, ObjectArray or an inheritor / implementing class of some of these interfaces.
See Also:
PArray.maxPossibleValue(double)

nBitCopies

public static BitArray nBitCopies(long n,
                                  boolean element)
Constructs an immutable unresizable bit array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nCharCopies

public static CharArray nCharCopies(long n,
                                    char element)
Constructs an immutable unresizable char array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nByteCopies

public static ByteArray nByteCopies(long n,
                                    byte element)
Constructs an immutable unresizable byte array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nShortCopies

public static ShortArray nShortCopies(long n,
                                      short element)
Constructs an immutable unresizable short array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nIntCopies

public static IntArray nIntCopies(long n,
                                  int element)
Constructs an immutable unresizable int array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nLongCopies

public static LongArray nLongCopies(long n,
                                    long element)
Constructs an immutable unresizable long array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nFloatCopies

public static FloatArray nFloatCopies(long n,
                                      float element)
Constructs an immutable unresizable float array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nDoubleCopies

public static DoubleArray nDoubleCopies(long n,
                                        double element)
Constructs an immutable unresizable double array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nObjectCopies

public static <T> ObjectArray<T> nObjectCopies(long n,
                                               T element)
Constructs an immutable unresizable Object array consisting of n copies of the specified element. The newly allocated data object is tiny (it contains a single instance of the element).

In the returned array:

Parameters:
n - the number of elements in the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.IllegalArgumentException - if n < 0.

nPCopies

public static PArray nPCopies(long n,
                              java.lang.Class<?> elementType,
                              double element)
Constructs an immutable unresizable array consisting of n copies of the specified double element, cast to the specified element type. More precisely, this method returns: Non-primitive element types are not allowed.

In the returned array:

Parameters:
n - the number of elements in the returned array.
elementType - the element type (primitive) of the returned array.
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.NullPointerException - if elementType is null.
java.lang.IllegalArgumentException - if n < 0 or if elementType is not boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class or double.class.

nPFixedCopies

public static PFixedArray nPFixedCopies(long n,
                                        java.lang.Class<?> elementType,
                                        long element)
Constructs an immutable unresizable array consisting of n copies of the specified integer element, cast to the specified element type. More precisely, this method returns: All other element types are not allowed.

In the returned array:

Parameters:
n - the number of elements in the returned array.
elementType - the element type of the returned array (boolean.class, char.class, byte.class, short.class, int.class or long.class).
element - the element to appear repeatedly in the returned array.
Returns:
an immutable unresizable array consisting of n copies of the specified element.
Throws:
java.lang.NullPointerException - if elementType is null.
java.lang.IllegalArgumentException - if n < 0 or if elementType is not boolean.class, char.class, byte.class, short.class, int.class or long.class.

nNullCopies

public static <T> ObjectArray<T> nNullCopies(long n,
                                             java.lang.Class<T> elementType)
The version of nObjectCopies(n, element) method with element=null that allows to specify the element type of the returned array. (For that method, the element type will be element.getClass(), but if element is null, the element type is always Object.class, that leads to problems while copying the created array to another object arrays.)

Parameters:
n - the number of null elements in the returned array.
elementType - the element type of the returned array.
Returns:
an immutable unresizable array consisting of n null elements.
Throws:
java.lang.IllegalArgumentException - if n < 0.

isNCopies

public static boolean isNCopies(Array array)
Returns true if the passed array is not null and was created by one of nXxxCopies methods of this class and, so, all array elements have the same constant value. This fact can be used for optimize loops where some elements are loaded from an array many times, for example:
 for (long disp = 0; disp < a.length(); disp += 1024) {
     if (!(disp > 0 && Arrays.isNCopies(a))) {
         // there is no sense to read data more than 1 time in a case of a constant array
         a.getData(disp, buffer);
     }
     // processing "buffer" Java array
 }
 

Such optimization is performed automatically while accessing a constant array via a data buffer.

Parameters:
array - the checked AlgART array (may be null, than the method returns false).
Returns:
true if the passed array was created by one of nXxxCopies methods of this class.

asIndexFuncArray

public static <T extends PArray> T asIndexFuncArray(Func f,
                                                    java.lang.Class<? extends T> requiredType,
                                                    long length)
Equivalent to asIndexFuncArray(true, f, requiredType, length).

Parameters:
f - the mathematical function used for calculating all result array elements.
requiredType - desired type of the returned array.
length - the length of the returned array.
Returns:
the array, defined by the passed function.
Throws:
java.lang.NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
java.lang.IllegalArgumentException - in the same situations as asIndexFuncArray(boolean, Func, Class, long) method.

asIndexFuncArray

public static <T extends PArray> T asIndexFuncArray(boolean truncateOverflows,
                                                    Func f,
                                                    java.lang.Class<? extends T> requiredType,
                                                    long length)
An analog of the asFuncArray(boolean, Func, Class, PArray...) method, where the passed function is applied not to the elements of some source array, but to the index of the resulting array. In other words, each element #k of the returned array is a result of calling f.get(k). So, this method does not require any source arrays.

The typical example is using ConstantFunc, when this method works alike nXxxCopies methods.

Please read comments to asFuncArray(boolean, Func, Class, PArray...) method about precise details of forming the elements of the returned array on the base of the real result of calling Func.get(double...) method.

Parameters:
truncateOverflows - specifies behavior of typecasting to int, short, byte and char resulting values (see comments to asFuncArray(boolean, Func, Class, PArray...) method).
f - the mathematical function used for calculating all result array elements.
requiredType - desired type of the returned array.
length - the length of the returned array.
Returns:
the array, defined by the passed function.
Throws:
java.lang.NullPointerException - if f or requiredType argument is null.
java.lang.IllegalArgumentException - if length is negative, or if requiredType is an inheritor of UpdatableArray (returned array must be immutable), or if requiredType is not one of classes BitArray.class, CharArray.class, ByteArray.class, ShortArray.class, IntArray.class, LongArray.class, FloatArray.class or DoubleArray.class. (Also IndexOutOfBoundsException is possible while further attempts to read elements from the returned AlgART array, if the passed function requires some arguments.)

asFuncArray

public static <T extends PArray> T asFuncArray(Func f,
                                               java.lang.Class<? extends T> requiredType,
                                               PArray... x)
Equivalent to asFuncArray(true, f, requiredType, x).

Parameters:
f - the mathematical function applied to all passed AlgART arrays.
requiredType - desired type of the returned array.
x - several AlgART arrays; at least one array must be passed.
Returns:
a view of the passed x arrays, defined by the passed function.
Throws:
java.lang.NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
java.lang.IllegalArgumentException - in the same situations as asFuncArray(boolean, Func, Class, PArray...) method.
SizeMismatchException - if x.length>1 and some of passed arrays have different lengths.

asFuncArray

public static <T extends PArray> T asFuncArray(boolean truncateOverflows,
                                               Func f,
                                               java.lang.Class<? extends T> requiredType,
                                               PArray... x)
Returns an immutable view of the passed x AlgART arrays (with primitive element type), where each element #k is a result of calling f.get(x[0].getDouble(k), x[1].getDouble(k), ...), i.e. the result of the passed function for arguments, equal to the corresponding elements #k in all passed arrays.

The array, returned by this method, is immutable, and its class implements one of the basic interfaces BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray or DoubleArray. The class of desired interface (one of 8 possible classes) must be passed as requiredType argument. For example, if requiredType=ByteArray.class, the returned array implements ByteArray.

If the required result type is not a DoubleArray, then some results of the calculated mathematical function f may not be directly interpreted as elements of the returned array: typecasting is necessary. This method performs necessary typecasting by the following algorithm.

Let's suppose that the source double value (result of calling f function) is v, and the necessary cast value (result of specific getXxx method in the returned array, for example, ByteArray.getByte(long)) is w.

The x argument is "vararg"; so you may pass a Java array as this argument. In this case, no references to the passed Java array are maintained by the result: it is cloned by this method.

The lengths of all passed x arrays must be equal; in other case, an exception is thrown.

In the returned array:

Important note. All calculations in the returned view are performed in the correct left-to-right order. More precisely, it means that any method, accessing the data in the returned array, works in the following (or strictly equivalent) way:

This behavior allows using this method for performing "in-place" algorithms, when the result of this method is copied into one of its x arguments (usually built by SimpleMemoryModel). Moreover, such algorithms will work correctly even if the arguments and the destination array are overlapping subarrays of a single AlgART array, if the starting offset of the destination array is not greater than the starting offsets of the arguments.

Parameters:
truncateOverflows - specifies behavior of typecasting to int, short, byte and char resulting values (see above).
f - the mathematical function applied to all passed AlgART arrays.
requiredType - desired type of the returned array.
x - several AlgART arrays; at least one array must be passed.
Returns:
a view of the passed x arrays, defined by the passed function.
Throws:
java.lang.NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
java.lang.IllegalArgumentException - if x.length==0 (no arrays passed), or if requiredType is an inheritor of UpdatableArray (returned array must be immutable), or if requiredType is not one of classes BitArray.class, CharArray.class, ByteArray.class, ShortArray.class, IntArray.class, LongArray.class, FloatArray.class or DoubleArray.class, or if the number of passed x arrays is insufficient for calculating the passed f function. (In the last situation, IllegalArgumentException may not occur immediately, but IndexOutOfBoundsException may occur instead of while further attempts to read elements from the returned AlgART array.)
SizeMismatchException - if x.length>1 and some of passed arrays have different lengths.
See Also:
asUpdatableFuncArray(boolean, net.algart.math.functions.Func.Updatable, Class, UpdatablePArray...)

asUpdatableFuncArray

public static <T extends UpdatablePArray> T asUpdatableFuncArray(Func.Updatable f,
                                                                 java.lang.Class<? extends T> requiredType,
                                                                 UpdatablePArray... x)
Equivalent to asUpdatableFuncArray(true, f, requiredType, x).

Parameters:
f - the mathematical function applied to all passed AlgART arrays.
requiredType - desired type of the returned array.
x - several AlgART arrays; at least one array must be passed.
Returns:
an updatable view of the passed arrays, defined by the passed function.
Throws:
java.lang.NullPointerException - if requiredType or x argument is null or if one of x arrays is null.
java.lang.IllegalArgumentException - in the same situations as asUpdatableFuncArray(boolean, net.algart.math.functions.Func.Updatable, Class, UpdatablePArray...) method.

asUpdatableFuncArray

public static <T extends UpdatablePArray> T asUpdatableFuncArray(boolean truncateOverflows,
                                                                 Func.Updatable f,
                                                                 java.lang.Class<? extends T> requiredType,
                                                                 UpdatablePArray... x)
An extended analog of the asFuncArray(boolean, Func, Class, PArray...) method allowing to create updatable view of the source array.

The asFuncArray(boolean, Func, Class, PArray...) method allows creating immutable views only: you cannot change the original arrays via the returned view. Unlike that, this method returns a mutable (updatable) view. Any changes of the elements in the returned array lead to corresponding changes of the elements of the original (underlying) array. Namely, setting some element #k of the returned view to the value w is equivalent to the following operations:

  1. getting the elements #k of the original arrays x by x[0].getDouble(k), x[1].getDouble(k), ... x[n-1].getDouble(k) calls into a temporary array double args[n];
  2. calling f.set(args, w) — this call should correct args elements (usually the first element);
  3. back saving the elements #k into the original arrays x by x[0].setDouble(k), x[1].setDouble(k), ... x[n-1].setDouble(k) calls.

The stage #1 may be skipped if the number of x arrays is 1. In this case, this method supposes that the f.set(args, w) has enough information to calculate args[0]: the result of the inverse function for w value.

As in the asFuncArray(boolean, Func, Class, PArray...) method, typecasting is required sometimes while setting elements. The rules of typecasting are the same as in that method; in particular, the truncateOverflows is used in the same manner.

The array, returned by this method, is unresizable, and its class implements one of the basic interfaces UpdatableBitArray, UpdatableCharArray, UpdatableByteArray, UpdatableShortArray, UpdatableIntArray, UpdatableLongArray, UpdatableFloatArray or UpdatableDoubleArray. The class of desired interface (one of 8 possible classes) must be passed as requiredType argument. For example, if requiredType=UpdatableByteArray.class or requiredType is some class implementing UpdatableByteArray, the returned array implements UpdatableByteArray.

In the returned array:

Parameters:
truncateOverflows - specifies behavior of typecasting to int, short, byte and char resulting values (see comments to asFuncArray(boolean, Func, Class, PArray...) method).
f - the mathematical function applied to all passed AlgART arrays.
requiredType - desired type of the returned array.
x - several AlgART arrays; at least one array must be passed.
Returns:
an updatable view of the passed arrays, defined by the passed function.
Throws:
java.lang.NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
java.lang.IllegalArgumentException - if x.length==0 (no arrays passed), or if requiredType is an inheritor of MutableArray (returned array must be immutable), or if requiredType is not one of classes UpdatableBitArray.class / BitArray.class, UpdatableCharArray.class / CharArray.class, UpdatableByteArray.class / ByteArray.class, UpdatableShortArray.class / ShortArray.class, UpdatableIntArray.class / IntArray.class, UpdatableLongArray.class / LongArray.class, UpdatableFloatArray.class / FloatArray.class or UpdatableDoubleArray.class / DoubleArray.class, or if the number of passed x arrays is insufficient for calculating the passed f function. (In the last situation, IllegalArgumentException may not occur immediately, but IndexOutOfBoundsException may occur instead of while further attempts to read or write elements from / to the returned AlgART array.)
SizeMismatchException - if x.length>1 and some of passed arrays have different lengths.
See Also:
asFuncArray(boolean, Func, Class, PArray...)

applyFunc

public static void applyFunc(ArrayContext context,
                             Func f,
                             UpdatablePArray result,
                             PArray... x)
Equivalent to applyFunc(context, f, true, result, x).

Parameters:
context - the context of copying; may be null, then it will be ignored.
f - the mathematical function applied to the source AlgART arrays.
result - the destination array.
x - the source arrays; may be empty; may include result array to provide "in-place" operations.
Throws:
java.lang.NullPointerException - if f, result, x or one of x arrays is null.
java.lang.IllegalArgumentException - if x.length==0 (no arrays passed), or if the number of passed x arrays is insufficient for calculating the passed f function. (In the last situation, IndexOutOfBoundsException may occur instead of while copying data to the result.)
SizeMismatchException - if x.length>1 and some of passed arrays have different lengths.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

applyFunc

public static void applyFunc(ArrayContext context,
                             boolean truncateOverflows,
                             Func f,
                             UpdatablePArray result,
                             PArray... x)
Equivalent to applyFunc(context, f, truncateOverflows, 0, true, result, x).

Parameters:
context - the context of copying; may be null, then it will be ignored.
truncateOverflows - the behavior of typecasting: see asFuncArray(boolean, Func, Class, PArray...).
f - the mathematical function applied to the source AlgART arrays.
result - the destination array.
x - the source arrays; may be empty; may include result array to provide "in-place" operations.
Throws:
java.lang.NullPointerException - if f, result, x or one of x arrays is null.
java.lang.IllegalArgumentException - if the number of passed x arrays is insufficient for calculating the passed f function. (In the last situation, IndexOutOfBoundsException may occur instead of while copying data to the result.)
SizeMismatchException - if some of passed arrays (result and some of x arrays) have different lengths.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

applyFunc

public static void applyFunc(ArrayContext context,
                             boolean truncateOverflows,
                             int numberOfTasks,
                             boolean strictMode,
                             Func f,
                             UpdatablePArray result,
                             PArray... x)
Creates a "lazy" array by lazy = asFuncArray(truncateOverflows, f, result.type(), x) call and copies it into the result argument by copy(context, result, lazy, numberOfTasks, strictMode) call.

In addition, this method checks, whether all passed arrays have the same length as result one, and throws an exception in other case.

If no source arrays are passed (x.length==0), the "lazy" array is created by another way: lazy = asIndexFuncArray(truncateOverflows, f, result.type(), result.length()).

Parameters:
context - the context of copying; may be null, then it will be ignored.
truncateOverflows - the behavior of typecasting: see asFuncArray(boolean, Func, Class, PArray...).
numberOfTasks - the desired number of parallel tasks; may be 0, then it will be chosen automatically.
strictMode - if false, optimization is allowed even if it can lead to little differences between the lazy and copied elements.
f - the mathematical function applied to the source AlgART arrays.
result - the destination array.
x - the source arrays; may be empty; may include result array to provide "in-place" operations.
Throws:
java.lang.NullPointerException - if f, result, x or one of x arrays is null.
java.lang.IllegalArgumentException - if the number of passed x arrays is insufficient for calculating the passed f function. (In the last situation, IndexOutOfBoundsException may occur instead of while copying data to the result.)
SizeMismatchException - if some of passed arrays (result and some of x arrays) have different lengths.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

isFuncArray

public static boolean isFuncArray(Array array)
Returns true if the passed array is not null functional array, created by this package. More precisely, if returns true if and only if the array is a result of one of the following methods: or if the array is the built-in array of some matrix, created by analogous methods in Matrices class: In a case of asFuncArray, asUpdatableFuncArray, asFuncMatrix, asUpdatableFuncMatrix methods, you may get the underlying arrays, passed to those methods in the last argument (or built-in arrays of underlying matrices in a case of Matrices methods) by getUnderlyingArrays(array) call, and get the used mathematical function by getFunc(Array) call.

If the array is an immutable view of another array, created by asUpdatableFuncArray(net.algart.math.functions.Func.Updatable, Class, UpdatablePArray...) or asUpdatableFuncArray(boolean, net.algart.math.functions.Func.Updatable, Class, UpdatablePArray...), this method also returns true, and getFunc(Array) also allows to get the used mathematical function. However, if the array is a Array.subArray(long, long) subarray} of some functional array, this method returns false.

Parameters:
array - the checked AlgART array (may be null, than the method returns false).
Returns:
true if the passed array a functional one.
See Also:
isIndexFuncArray(Array)

isIndexFuncArray

public static boolean isIndexFuncArray(Array array)
Returns true if the passed array is not null functional array, created by this package, calculated on the base of array indexes only, not depending on another arrays/matrices. More precisely, it returns true if and only if the array is a result of one of the following calls: or by equivalent methods like Matrices.asResized(Matrices.ResizingMethod, Matrix, long...), based on these calls.

Parameters:
array - the checked AlgART array (may be null, than the method returns false).
Returns:
true if the passed array a functional one, calculated on the base of array indexes only.
See Also:
isFuncArray(Array), Matrices.isCoordFuncMatrix(Matrix)

getFunc

public static Func getFunc(Array array)
Returns the mathematical function, used for creating the passed functional array, or throws an exception if this array is not functional. The returned function is the same function that was passed to the method, called to created the passed array:

Parameters:
array - the functional AlgART array.
Returns:
the mathematical function, used for creating it.
Throws:
java.lang.NullPointerException - if the argument is null.
java.lang.IllegalArgumentException - if the passed array is not functional, i.e. if isFuncArray(Array) returns false for it.
See Also:
isFuncArray(Array)

getTruncationMode

public static boolean getTruncationMode(Array array)
Returns the value of truncateOverflows argument of asFuncArray(boolean, Func, Class, PArray...) method (or one of its overloaded versions), used for creating the passed functional array, or throws an exception if this array is not functional.

Parameters:
array - the functional AlgART array.
Returns:
the truncation mode, used for creating it.
Throws:
java.lang.NullPointerException - if the argument is null.
java.lang.IllegalArgumentException - if the passed array is not functional, i.e. if isFuncArray(Array) returns false for it.
See Also:
isFuncArray(Array)

getIndexDimensions

public static long[] getIndexDimensions(Array array)
Returns the dimensions of the matrix, coordinates of which are used as arguments of the underlying function in the passed index-based functional array, or throws an exception if this array is not a functional array, calculated on the base of indexes. More precisely, if the passed array is created by the methods this method returns a Java array with the only element {array.length()}; if the passed array is an underlying array of some matrix m, created by the methods this method returns the matrix dimensions m.dimensions(); in other cases this method throws IllegalArgumentException.

Parameters:
array - the index-based functional array.
Returns:
the dimensions of the matrix, coordinates of which are used as arguments of the underlying function.
Throws:
java.lang.NullPointerException - if the argument is null.
java.lang.IllegalArgumentException - if the passed array is not index-based functional, i.e. if isIndexFuncArray(Array) returns false for it.
See Also:
isIndexFuncArray(Array)

asConcatenation

public static Array asConcatenation(Array... arrays)
Returns an immutable view of the passed sequence of AlgART arrays as their concatenation. More precisely, the returned array has the length, equal to the sum of lengths l0, l1, ..., ln−1 of all passed arrays, and the element #k of the returned array is the element #k-(l0+l1+...+li) in arrays[i], where i is the last index, for which k>=l0+l1+...+li. Query operations on the returned array "read through" to corresponding source arrays.

All passed arrays must be unresizable and have the same element type; in other case, an exception is thrown.

The array, returned by this method, is immutable. Its class implements the same basic interface BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray or ObjectArray as all passed arrays. The element type of the returned array is the same as the element type of the passed ones.

In the returned array:

Parameters:
arrays - the sequence of AlgART arrays.
Returns:
the concatenation of these arrays.
Throws:
java.lang.NullPointerException - if arrays argument is null.
java.lang.IllegalArgumentException - if arrays.length==0 (no arrays passed), of if some of the passed arrays are not unresizable, or if they have different element types.
TooLargeArrayException - if the sum of lengths of the passed arrays is greater than Long.MAX_VALUE=263−1.

isConcatenation

public static boolean isConcatenation(Array array)
Returns true if the passed array is a concatenation view, i.e. is a result of asConcatenation(Array...) method. In this case, you may get the underlying array, passed to those methods in the last argument, by getUnderlyingArrays(array) call.

Please note: if the array is a subarray of some concatenation view, this method usually returns true, but may return false if the subarray does not intersect bounds between concatenated arrays.

Parameters:
array - the checked AlgART array (may be null, than the method returns false).
Returns:
true if the passed array a concatenation view of other arrays.

asShifted

public static Array asShifted(Array array,
                              long shift)
Returns an immutable view of the passed AlgART array, cyclically shifted to the right by the specified number of elements. More precisely, the returned array has the same length, and the element #k of the returned array is the element #((k-shift) mod length) of the passed array, where a mod b (b>=0) is a "positive remainder": a%b if a>=0 or b+a%b if a<0. (If the array length=0, the shift argument is ignored and the returned array contains no elements.)

The passed array must be unresizable; in other case, an exception is thrown.

The array, returned by this method, is immutable. Its class implements the same basic interface BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray or ObjectArray as the passed array. The element type of the returned array is the same as the element type of the passed one.

In the returned array:

Parameters:
array - the source AlgART array.
shift - the shift (to the right) of the index in the returned view.
Returns:
a shifted view of the passed array.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IllegalArgumentException - if the passed array is not unresizable.

isShifted

public static boolean isShifted(Array array)
Returns true if the passed array is not null shifted array, i.e. is a result of asShifted(Array, long) method. In this case, you may get the underlying array, passed to those methods in the last argument, by getUnderlyingArrays(array)[0] call, and get the used shift by getShift(Array) call.

Please note: if the array is a Array.subArray(long, long) subarray} of some shifted array, this method returns false.

Please note: if the array is a subarray of some shifted array, this method may return both true and false, depending on bounds of the subarray.

Parameters:
array - the checked AlgART array (may be null, than the method returns false).
Returns:
true if the passed array a shifted array.

getShift

public static long getShift(Array array)
Returns the shift, used for creating the passed shited array, or throws an exception if this array is not shifted. The returned shift is equal to the corresponding argument that was passed to asShifted(Array, long) method, which was called to create the passed array.

Parameters:
array - the functional AlgART array.
Returns:
the mathematical function, used for creating it.
Throws:
java.lang.NullPointerException - if the argument is null.
java.lang.IllegalArgumentException - if the passed array is not shifted, i.e. if isShifted(Array) returns false for it.
See Also:
isShifted(Array)

copy

public static Arrays.CopyStatus copy(ArrayContext context,
                                     UpdatableArray dest,
                                     Array src)
Copies min(dest.length(), src.length()) elements of src array, starting from index 0, to dest array, starting from index 0.

This method works alike UpdatableArray.copy(Array) with two important differences.

  1. This method performs copying in several threads. It may be very important on multiprocessor or multi-core computers for the case, when the source array is a "lazy" view of another arrays, that is when reading data from it means performing complex algorithm calculating the data. The good example is an array returned by asFuncArray(Func, Class, PArray...), when the result of this method is calculated on the base of tens or hundreds source arrays passed in the last argument. In this situation, performing this method really means actual execution of the algorithm, and several threads allow to use all system processors for this purpose.
    Multithread copying is performed by a thread pool: java.util.concurrent.ExecutorService. The full copying procedure is split into several tasks, where each task copies some set of regions of src array to the corresponding regions of dest array. All tasks are submitted to the thread pool, and then this method waits until all tasks will be completed. The thread pool, performing the multithread copying, and the number of copying tasks are gotten by the methods of context.getThreadPoolFactory() object; if context argument is null, the DefaultThreadPoolFactory instance is created and used.
    Note: if this method may suppose that the passed array is not "lazy", namely, if !src.isLazy(), it uses only 1 task and ignores result of ThreadPoolFactory.recommendedNumberOfTasks(Array) method. In this situation, it's very probable that copying is simple transferring data between memory and/or disk; such operations are not optimized usually by multithreading technique.
    Note: if the number of parallel tasks is 1, this method performs copying in the current thread and does not use the thread pool at all.
     
  2. If the context argument is not null, this method periodically calls its updateProgress and checkInterruption methods. More precisely, this method periodically calls ArrayContext.checkInterruption() method, catching any possible RuntimeException thrown by it, and, immediately after this, calls ArrayContext.updateProgress(net.algart.arrays.ArrayContext.Event) with correctly filled ArrayContext.Event instance. If ArrayContext.checkInterruption() has thrown some RuntimeException, all running threads are interrupted as soon as possible, and, when they will be finished, the same exception is thrown by this method. This technique allows to show the progress of execution to the end user and to interrupt the copying by some UI command if this method works for too long time.

Usually this method performs copying by a sequence of calls dest.subArr(p, len).copy(array.subArr(p, len)), where p is the position inside arrays and len is the length of the copied portion, usually several tens of thousands elements. But in some special cases this method uses more complex algorithms of copying.

In addition to calling ArrayContext.checkInterruption(), this method also interrupts all running threads, if the current thread, that calls this method, is interrupted by the standard Thread.interrupt() call. In this (and only this) case, this method throws java.io.IOError. Usually, you should avoid interrupting the threads, processing AlgART arrays, via Thread.interrupt() technique: see the package description about runtime exceptions issue.

Alike UpdatableArray.copy(Array) method, some elements may be copied incorrectly if this array and src are views of the same data, and the swapped data areas overlap. Unlike UpdatableArray.copy(Array), this problem occurs even for arrays, created by SimpleMemoryModel. But if the copied areas of the underlying data are the same (for example, if src if some view of this array generated by asFuncArray, but not asShifted method), this method works correctly: any elements will be read before they will be updated.

This method works only if the element types of this and src arrays (returned by Array.elementType()) are the same, or (for non-primitive elements) if this element type is a superclass of the source element type.

For non-primitive element type (ObjectArray, UpdatableObjectArray, MutableObjectArray subinterfaces), this method may copy only references to elements, but also may copy the content of elements: it depends on implementation.

Parameters:
context - the context of copying; may be null, then it will be ignored.
dest - the destination array.
src - the source array.
Returns:
the information about copying.
Throws:
java.lang.NullPointerException - if src or dest argument is null.
java.lang.IllegalArgumentException - if the source and destination element types do not match.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).
See Also:
copy(ArrayContext, UpdatableArray, Array, int), copy(ArrayContext, UpdatableArray, Array, int, boolean), Arrays.ParallelExecutor, Arrays.Copier

copy

public static Arrays.CopyStatus copy(ArrayContext context,
                                     UpdatableArray dest,
                                     Array src,
                                     int numberOfTasks)
This method is an analog of copy(ArrayContext, UpdatableArray, Array), allowing to specify the number of parallel tasks. More precisely, if numberOfTasks argument is positive, then the number of tasks submitted to the thread pool will be equal to this argument, regardless of the result of ThreadPoolFactory.recommendedNumberOfTasks(Array) method and of the "lazy" or "new" status of the source array. If numberOfTasks==0, this method is strictly equivalent to copy(ArrayContext, UpdatableArray, Array).

This method can be convenient, for example, if you are sure that multithreading is not useful in a concrete algorithm and the number of tasks should be 1.

Parameters:
context - the context of copying; may be null, then it will be ignored.
dest - the destination array.
src - the source array.
numberOfTasks - the desired number of parallel tasks; may be 0, then it will be chosen automatically.
Returns:
the information about copying.
Throws:
java.lang.NullPointerException - if src or dest argument is null.
java.lang.IllegalArgumentException - if the source and destination element types do not match, or if the numberOfThreads argument is negative.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).
See Also:
copy(ArrayContext, UpdatableArray, Array), copy(ArrayContext, UpdatableArray, Array, int, boolean), Arrays.ParallelExecutor, Arrays.Copier

copy

public static Arrays.CopyStatus copy(ArrayContext context,
                                     UpdatableArray dest,
                                     Array src,
                                     int numberOfTasks,
                                     boolean strictMode)
This method is an analog of copy(ArrayContext, UpdatableArray, Array) and copy(ArrayContext, UpdatableArray, Array, int) providing a special "non-strict" copying mode.

Namely, if strictMode argument is false, then in some cases this method may copy elements with little errors (distortions). The probability and numeric value of errors is very low. The only reason of possible errors is limited precision of floating-point calculations.

The purpose of the non-strict mode is optimization: copying of some "lazy" arrays is performed much faster in this mode. For example, the result of Matrices.asResized (its built-in array) is copied faster in 10 and more times, when the source (non-resized) matrix is not created by SimpleMemoryModel.

If strictMode=true, this method is equivalent to copy(ArrayContext context, UpdatableArray dest, Array src, int numberOfTasks).

Parameters:
context - the context of copying; may be null, then it will be ignored.
dest - the destination array.
src - the source array.
numberOfTasks - the desired number of parallel tasks; may be 0, then it will be chosen automatically.
strictMode - if false, optimization is allowed even if it can lead to little differences between the source and copied elements.
Returns:
the information about copying.
Throws:
java.lang.NullPointerException - if src or dest argument is null.
java.lang.IllegalArgumentException - if the source and destination element types do not match, or if the numberOfThreads argument is negative.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).
See Also:
copy(ArrayContext, UpdatableArray, Array)

compareAndCopy

public static Arrays.ComparingCopyStatus compareAndCopy(ArrayContext context,
                                                        UpdatableArray dest,
                                                        Array src)
This method is an analog of copy(ArrayContext, UpdatableArray, Array) allowing to know, whether the destination array was really modified while copying. Namely, this method performs the same things as copy(ArrayContext context, UpdatableArray dest, Array src) and returns the status, where Arrays.ComparingCopyStatus.changed() method returns true if and only if at least one element of the dest array was changed as a result of copying from src array, in terms of the Array.equals(Object) method.

Parameters:
context - the context of copying; may be null, then it will be ignored.
dest - the destination array.
src - the source array.
Returns:
the information about copying.
Throws:
java.lang.NullPointerException - if src or dest argument is null.
java.lang.IllegalArgumentException - if the source and destination element types do not match.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

rangeOf

public static Range rangeOf(PArray array,
                            Arrays.MinMaxInfo minMaxInfo)
Equivalent to rangeOf(null, array, minMaxInfo).

Parameters:
array - some primitive array.
minMaxInfo - the object where to store the indexes and values of found minimum and maximum; may be null if you need only the values of the minimum and maximum.
Returns:
the values of the found minimal and maximal elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

rangeOf

public static Range rangeOf(ArrayContext context,
                            PArray array,
                            Arrays.MinMaxInfo minMaxInfo)
Returns a Range.valueOf(min, max), where min is equal to the minimal array element and min is equal to the maximal array element. The elements are extracted by array.getDouble(k) method (or by an equivalent technique).

Please remember that ByteArray and ShortArray are interpreted as unsigned.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

If the minMaxInfo argument is not null, the indexes of the found minimum / maximum, as well as the returned range, are stored in this object, and this object becomes initialized. In future, this information may be retrieved by the corresponding methods of Arrays.MinMaxInfo class. If there are several elements equal to the minimum, the index of minimum, stored in this object, may contain an index of any such element. If there are several elements equal to the maximum, the index of maximum, stored in this object, may contain an index of any such element.

If the passed array is empty (its length is 0), the method returns 0..0 range (Range.valueOf(0.0, 0.0)). In this case, if the minMaxInfo argument is not null, the indexes of the minimum / maximum, stored in this object, will be equal to -1.

Please note that the Arrays.MinMaxInfo class is internally synchronized and, so, thread-safe. It can be useful if you call this method in a separate thread and need to use the calculated information after finishing this method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
minMaxInfo - the object where to store the indexes and values of found minimum and maximum; may be null if you need only the values of the minimum and maximum.
Returns:
the values of the found minimal and maximal elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

rangeOf

public static Range rangeOf(PArray array)
Equivalent to rangeOf(null, array, null).

Parameters:
array - some primitive array.
Returns:
the values of the found minimal and maximal elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

rangeOf

public static Range rangeOf(ArrayContext context,
                            PArray array)
Equivalent to rangeOf(context, array, null).

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
Returns:
the values of the found minimal and maximal elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

sumOf

public static double sumOf(PArray array)
Equivalent to sumOf(null, array).

Parameters:
array - some primitive array.
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

sumOf

public static double sumOf(ArrayContext context,
                           PArray array)
Returns the sum of all array elements: the results of array.getDouble(k) for all k==0,1,...,array.length()-1.

This method works in strictfp mode: the result will be absolutely same on all platforms.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. However, unlike that method, this method is always performed in a single thread and does not use multithreading for optimization. It is necessary to provide absolutely identical results while different calls (because the floating-point sum can depend on the order of summing).

Please remember that ByteArray and ShortArray are interpreted as unsigned.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

preciseSumOf

public static long preciseSumOf(PFixedArray array,
                                boolean checkOverflow)
                         throws java.lang.ArithmeticException
Equivalent to preciseSumOf(null, array, checkOverflow).

Parameters:
array - some primitive array, excluding floating point arrays.
checkOverflow - whether overflow should lead to ArithmeticException
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.ArithmeticException - if checkOverflow is true and the result or some partial sum cannot be represented by long value.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

preciseSumOf

public static long preciseSumOf(ArrayContext context,
                                PFixedArray array,
                                boolean checkOverflow)
                         throws java.lang.ArithmeticException
Returns the integer sum of all array elements: the results of array.getLong(k) for all k==0,1,...,array.length()-1.

The result is the same as the sum calculated by the following loop:

 long sum = 0;
 for (long k = 0; k < array.length(); k++)
     sum += array.getLong(k);
 

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

In a case of overflow (when 64 bits are not enough to represent the result or some partial sum), the behavior depends on checkOverflow argument. If it is false, the result will be incorrect: it will contain 64 lowest bits of the precise sum. If checkOverflow is true, the ArithmeticException will be thrown; in this situation, if the exception is not thrown, you can be sure that this method returns the correct result.

Please remember that ByteArray and ShortArray are interpreted as unsigned.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array, excluding floating point arrays.
checkOverflow - whether overflow should lead to ArithmeticException
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.ArithmeticException - if checkOverflow is true and the result or some partial sum cannot be represented by long value.

preciseSumOf

public static long preciseSumOf(PFixedArray array)
Equivalent to preciseSumOf(null, array, false).

Parameters:
array - some primitive array, excluding floating point arrays.
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

preciseSumOf

public static long preciseSumOf(ArrayContext context,
                                PFixedArray array)
Equivalent to preciseSumOf(context, array, false).

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array, excluding floating point arrays.
Returns:
the sum of all array elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

cardinality

public static long cardinality(ArrayContext context,
                               BitArray bitArray)
Returns the number of bits set to true in this array. Equivalent to preciseSumOf(context, bitArray).

Parameters:
context - the context of calculations; may be null, then it will be ignored.
bitArray - the bit array.
Returns:
the number of bits set to true in this array.
Throws:
java.lang.NullPointerException - if bitArray argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

cardinality

public static long cardinality(BitArray bitArray)
Returns the number of bits set to true in this array. Equivalent to preciseSumOf(bitArray).

Parameters:
bitArray - the bit array.
Returns:
the number of bits set to true in this array.
Throws:
java.lang.NullPointerException - if bitArray argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

histogramOf

public static boolean histogramOf(PArray array,
                                  long[] histogram,
                                  double from,
                                  double to)
Equivalent to histogramOf(null, array, histogram, from, to).

Parameters:
array - some primitive array.
histogram - the histogram to be incremented: histogram.length columns between from and to.
from - the low boundary for the counted values, inclusive.
to - the high boundary for the counted values, exclusive.
Returns:
whether all elements of the array are inside the range from..to.
Throws:
java.lang.NullPointerException - if array or histogram argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

histogramOf

public static boolean histogramOf(ArrayContext context,
                                  PArray array,
                                  long[] histogram,
                                  double from,
                                  double to)
Increments the histogram of frequency of values in the passed array. The histogram corresponds to values in the range from <= v < to.

More precisely, if from < to, then for every element #k of the passed AlgART array this method:

  1. gets its real value v = array.getDouble(k);
  2. calculates the index of the column in the histogram: m = (int)StrictMath.floor((v - from) * multiplier), where multiplier = histogram.length / (to - from);
  3. if this index lies in the range 0 <= m < histogram.length, increments the corresponding element of the passed histogram Java array: histogram[m]++

The result of this method will be true if the index m at the step 3 always fulfilled the condition 0 <= m < histogram.length, or false if this index was out of range at least for one element. If from >= to, this method does nothing and returns false. If the passed array is empty (array.length()==0), this method returns true if from < to and false if from >= to.

Please draw attention to the formula at the step 2. It differs from the more obvious formula (int)((v-from)/(to-from)*histogram.length) and theoretically can lead to little other results.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

This method works in strictfp mode: the results will be absolutely same on all platforms.

Please remember that ByteArray and ShortArray are interpreted as unsigned.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
histogram - the histogram to be incremented: histogram.length columns between from and to.
from - the low boundary for the counted values, inclusive.
to - the high boundary for the counted values, exclusive.
Returns:
whether all elements of the array are inside the range from..to.
Throws:
java.lang.NullPointerException - if array or histogram argument is null.
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).

packBitsGreater

public static void packBitsGreater(UpdatableBitArray bits,
                                   PArray array,
                                   double threshold)
Equivalent to packBitsGreater(null, bits, array, threshold).

Parameters:
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

packBitsGreater

public static void packBitsGreater(ArrayContext context,
                                   UpdatableBitArray bits,
                                   PArray array,
                                   double threshold)
Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) >= threshold. Works much faster than the simple loop of such checks.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
packBitsLess(ArrayContext, UpdatableBitArray, PArray, double)

packBitsLess

public static void packBitsLess(UpdatableBitArray bits,
                                PArray array,
                                double threshold)
Equivalent to packBitsLess(null, bits, array, threshold).

Parameters:
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

packBitsLess

public static void packBitsLess(ArrayContext context,
                                UpdatableBitArray bits,
                                PArray array,
                                double threshold)
Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) <= threshold. Works much faster than the simple loop of such checks.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
packBitsGreater(ArrayContext, UpdatableBitArray, PArray, double)

packBitsGreaterOrEqual

public static void packBitsGreaterOrEqual(UpdatableBitArray bits,
                                          PArray array,
                                          double threshold)
Equivalent to packBitsGreaterOrEqual(null, bits, array, threshold).

Parameters:
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

packBitsGreaterOrEqual

public static void packBitsGreaterOrEqual(ArrayContext context,
                                          UpdatableBitArray bits,
                                          PArray array,
                                          double threshold)
Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) >= threshold. Works much faster than the simple loop of such checks.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
packBitsLessOrEqual(ArrayContext, UpdatableBitArray, PArray, double)

packBitsLessOrEqual

public static void packBitsLessOrEqual(UpdatableBitArray bits,
                                       PArray array,
                                       double threshold)
Equivalent to packBitsLessOrEqual(null, bits, array, threshold).

Parameters:
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

packBitsLessOrEqual

public static void packBitsLessOrEqual(ArrayContext context,
                                       UpdatableBitArray bits,
                                       PArray array,
                                       double threshold)
Sets every bit #k of the passed updatable bit array to the boolean value array.getDouble(k) <= threshold. Works much faster than the simple loop of such checks.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
bits - the bit array that will contain results of comparison of the passed array with the threshold.
array - some primitive array that should be compared with the threshold.
threshold - the threshold that will be compared with all elements of array.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
packBitsGreaterOrEqual(ArrayContext, UpdatableBitArray, PArray, double)

unpackBits

public static void unpackBits(UpdatablePArray array,
                              BitArray bits,
                              double filler0,
                              double filler1)
Equivalent to unpackBits(null, array, bits, filler0, filler1).

Parameters:
array - some primitive array.
bits - the bit array that should be "unpacked" to array.
filler0 - the value that will be set in array for zero bits.
filler1 - the value that will be set in array for unit bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

unpackBits

public static void unpackBits(ArrayContext context,
                              UpdatablePArray array,
                              BitArray bits,
                              double filler0,
                              double filler1)
Sets every element #k of the passed updatable array to filler0 value, if the corresponding element #k of bits array is false (0), or to filler1, if this bit is true (1). Equivalent to the loop of the operators
 array.setDouble(k, bits.getBit(k) ? filler1 : filler0)
 

for all indexes k, but works much faster than the simple loop.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

This method is also equivalent to the following code:

 Class et = array.elementType();
 if (et == byte.class || et == short.class || et == int.class || et == char.class) {
     filler0 = (int)filler0;
     filler1 = (int)filler1;
 }
 Arrays.applyFunc(context, false,
     SelectConstantFunc.getInstance(filler0, filler1), array, bits);
 

(Additional casting to int is necessary here due to different type cast rules in UpdatablePArray.setDouble(long, double) and asFuncArray methods.)

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
bits - the bit array that should be "unpacked" to array.
filler0 - the value that will be set in array for zero bits.
filler1 - the value that will be set in array for unit bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
unpackUnitBits(ArrayContext, UpdatablePArray, BitArray, double), unpackZeroBits(ArrayContext, UpdatablePArray, BitArray, double)

unpackUnitBits

public static void unpackUnitBits(UpdatablePArray array,
                                  BitArray bits,
                                  double filler1)
Equivalent to unpackUnitBits(null, array, bits, filler1).

Parameters:
array - some primitive array.
bits - the bit array, the unit elements of which should be "unpacked" to array.
filler1 - the value that will be set in array for unit bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

unpackUnitBits

public static void unpackUnitBits(ArrayContext context,
                                  UpdatablePArray array,
                                  BitArray bits,
                                  double filler1)
Sets every element #k of the passed updatable array to filler1 value, if the corresponding element #k of bits array is true (1), or doesn't change it, if this bit is false (0). Equivalent to the loop of the operators
 if (bits.getBit(k))
     array.setDouble(k, filler1)
 

for all indexes k, but works much faster than the simple loop.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
bits - the bit array, the unit elements of which should be "unpacked" to array.
filler1 - the value that will be set in array for unit bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
unpackBits(ArrayContext, UpdatablePArray, BitArray, double, double), unpackZeroBits(ArrayContext, UpdatablePArray, BitArray, double)

unpackZeroBits

public static void unpackZeroBits(UpdatablePArray array,
                                  BitArray bits,
                                  double filler0)
Equivalent to unpackZeroBits(null, array, bits, filler0).

Parameters:
array - some primitive array.
bits - the bit array, the zero elements of which should be "unpacked" to array.
filler0 - the value that will be set in array for zero bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.

unpackZeroBits

public static void unpackZeroBits(ArrayContext context,
                                  UpdatablePArray array,
                                  BitArray bits,
                                  double filler0)
Sets every element #k of the passed updatable array to filler0 value, if the corresponding element #k of bits array is false (0), or doesn't change it, if this bit is true (1). Equivalent to the loop of the operators
 if (!bits.getBit(k))
     array.setDouble(k, filler0)
 

for all indexes k, but works much faster than the simple loop.

The context argument is used in the same manner as in copy(ArrayContext, UpdatableArray, Array) method. Namely, the context allows to specify the desired number of parallel tasks, provide the pool factory, interrupt this method and show its progress. If the context argument is null, then this method still may use several threads, if DefaultThreadPoolFactory instance recommends it, and may be interruptable by Thread.interrupt(), alike copy(ArrayContext, UpdatableArray, Array) method.

Parameters:
context - the context of calculations; may be null, then it will be ignored.
array - some primitive array.
bits - the bit array, the zero elements of which should be "unpacked" to array.
filler0 - the value that will be set in array for zero bits.
Throws:
java.lang.NullPointerException - if array or bits argument is null.
SizeMismatchException - if array.length()!=bits.length().
java.io.IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
See Also:
unpackBits(ArrayContext, UpdatablePArray, BitArray, double, double), unpackUnitBits(ArrayContext, UpdatablePArray, BitArray, double)

zeroFill

public static void zeroFill(UpdatableArray array)
Fills all elements of the array by zero (0 for numbers, false for boolean values, null or some "empty" objects for non-primitive elements).

Parameters:
array - the filled array.
Throws:
java.lang.NullPointerException - if array argument is null.
See Also:
UpdatablePArray.fill(double), UpdatablePArray.fill(long)

toJavaArray

public static java.lang.Object toJavaArray(Array array)
Returns a Java array containing all of the elements in this AlgART array in proper sequence, if the length of this array is not too high (not greater than Integer.MAX_VALUE). In other case, throws TooLargeArrayException. The length of returned Java array will be equal to current array.length(), and array elements will be stored in elements #0..#length()-1} of the returned array.

The returned Java array will be "safe" in that no references to it are maintained by this array. (In other words, this method must always allocate a new Java array). The caller is thus free to modify the returned array.

The type of returned array is always one of the following:

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
Array.getData(long, Object)

toJavaArray

public static boolean[] toJavaArray(BitArray array)
Equivalent to (boolean[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static char[] toJavaArray(CharArray array)
Equivalent to (char[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static byte[] toJavaArray(ByteArray array)
Equivalent to (byte[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static short[] toJavaArray(ShortArray array)
Equivalent to (short[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static int[] toJavaArray(IntArray array)
Equivalent to (int[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static long[] toJavaArray(LongArray array)
Equivalent to (long[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static float[] toJavaArray(FloatArray array)
Equivalent to (float[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static double[] toJavaArray(DoubleArray array)
Equivalent to (double[])toJavaArray((Array)array).

Parameters:
array - the source AlgART array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toJavaArray

public static <E> E[] toJavaArray(ObjectArray<E> array)
Equivalent to (E[])toJavaArray((Array)array).

Parameters:
array - the source AlgART object array.
Returns:
Java array containing all of the elements in this array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
toJavaArray(Array), Array.getData(long, Object)

toString

public static java.lang.String toString(CharArray charArray)
Returns a string containing all characters in this character array (in the same order as in this array). The length of the string will be equal to charArray.length().

Parameters:
charArray - the source array.
Returns:
a string containing all characters in this character array.
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
See Also:
Array.toString()

toString

public static java.lang.String toString(Array array,
                                        java.lang.String separator,
                                        int maxStringLength)
Joins and returns as a string the standard string representations for all elements of the AlgART array, separating elements by the given separator.

For arrays of boolean elements (BitArray), "false" and "true" words are used as representation. For integer arrays (ByteArray, ShortArray, IntArray, LongArray), the signed decimal representation is used. For arrays of char elements (CharArray), the unsigned decimal representation is used. For arrays of objects (ObjectArray), the null elements are represented as "null" string, and non-null elements are converted to strings by their toString method.

If the necessary string length exceeds maxStringLength characters, this method break joining after the element, which leads to exceeding this limit, and adds "..." instead of all further elements. So, the length of returning string will never be essentially larger than maxStringLength characters. You may specify Integer.MAX_VALUE as maxStringLength value to be sure that all array elements will be joined.

If the passed array is empty, returns the empty string ("").

Parameters:
array - the source AlgART array.
separator - the string used for separating elements.
maxStringLength - the maximal allowed length of returned string (longer results are truncated with adding "..." at the end).
Returns:
the string representations of all elements joined into one string.
Throws:
java.lang.NullPointerException - if array or separator argument is null
java.lang.IllegalArgumentException - if maxStringLength <= 0.
See Also:
toString(Array, Locale, String, String, int), toHexString(Array, String, int), JArrays.toString(boolean[], String, int), JArrays.toString(char[], String, int), JArrays.toString(byte[], String, int), JArrays.toString(short[], String, int), JArrays.toString(int[], String, int), JArrays.toString(long[], String, int), JArrays.toString(float[], String, int), JArrays.toString(double[], String, int), JArrays.toString(Object[], String, int)

toString

public static java.lang.String toString(Array array,
                                        java.util.Locale locale,
                                        java.lang.String format,
                                        java.lang.String separator,
                                        int maxStringLength)
Joins and returns as a string the string representations for all elements of the AlgART array, separating elements by the given separator, using format string for formatting numeric elements.

This method works alike toString(Array, String, int), with the only difference that byte, short, int, long, float and double elements are converted to string with the specified format by String.format method. For array types BitArray, CharArray and ObjectArray this method is equivalent to toString(array, separator, maxStringLength).

Parameters:
array - the source AlgART array.
locale - the locale that will be passed to String.format(locale,format,v) call.
format - format string for numeric elements: each element v is converted to string by String.format(locale,format,v) call.
separator - the string used for separating elements.
maxStringLength - the maximal allowed length of returned string (longer results are truncated with adding "..." at the end).
Returns:
the string representations of all elements joined into one string.
Throws:
java.lang.NullPointerException - if array or separator argument is null.
java.lang.IllegalArgumentException - if maxStringLength <= 0.
See Also:
toString(Array, String, int), JArrays.toString(byte[], Locale, String, String, int), JArrays.toString(short[], Locale, String, String, int), JArrays.toString(int[], Locale, String, String, int), JArrays.toString(long[], Locale, String, String, int), JArrays.toString(float[], Locale, String, String, int), JArrays.toString(double[], Locale, String, String, int)

toHexString

public static java.lang.String toHexString(Array array,
                                           java.lang.String separator,
                                           int maxStringLength)
Joins and returns as a string the "hexadecimal" string representations for all elements of the AlgART array, separating elements by the given separator.

The result will be the same as for toString(Array, String, int) method, beside the following:

Parameters:
array - the source AlgART array.
separator - the string used for separating elements.
maxStringLength - the maximal allowed length of returned string (longer results are truncated with adding "..." at the end).
Returns:
the string representations of all elements joined into one string.
Throws:
java.lang.NullPointerException - if array or separator argument is null.
java.lang.IllegalArgumentException - if maxStringLength <= 0.
See Also:
toString(Array, String, int), JArrays.toBinaryString(boolean[], String, int), JArrays.toHexString(char[], String, int), JArrays.toHexString(byte[], String, int), JArrays.toHexString(short[], String, int), JArrays.toHexString(int[], String, int), JArrays.toHexString(long[], String, int)

lengthUnsigned

public static void lengthUnsigned(MutableArray array,
                                  long newUnsignedLength)
Equivalent to MutableArray.length(long) method with the only exception that newUnsignedLength is considered as unsigned long value. More precisely, this method throws TooLargeArrayException if newUnsignedLength<0 (for unsigned values, it means that the number >=263); in other case, this method just calls array.length(newUnsignedLength).

This method is convenient if you need to set the new length to a sum a+b of 2 long values a and b (usual signed positive long values), but you are not sure that this sum cannot exceed Long.MAX_VALUE=263-1 limit. For example, let a is some resizable array and you need to increase its length by some positive incr value. If, due to some bug, incr is too large (as Long.MAX_VALUE), then the call a.length(a.length()+incr) can reduce the array length, but the call Arrays.length(a, a.length()+incr) works correctly: throws an exception.

Parameters:
array - an array to be resized.
newUnsignedLength - new array length (unsigned).
Throws:
java.lang.NullPointerException - if array argument is null.
TooLargeArrayException - if the sum array.length()+newUnsignedLength exceeds Long.MAX_VALUE limit.

goodStartOffsetInArrayOfLongs

public static int goodStartOffsetInArrayOfLongs(BitArray bitArray,
                                                long position,
                                                int maxAvailableGap)
Returns the minimal offset=0..maxAvailableGap-1, for which the calls getBits(position, destArray, offset, someCount) and (for updatable array) setBits(position, srcArray, offset, someCount) work essentially faster than for most of other ("slow") positions, or 0 if there is no such offset, in particular, if position>=length().

This result is based on the call bitArray.nextQuickPosition. More precisely, this method returns
    (int)(position - quickPosition) % maxAvailableGap,
where
    quickPosition = bitArray.nextQuickPosition(position - Math.max(maxAvailableGap, 64)).
(Subtracting max(maxAvailableGap, 64) does not change the result in a usual case, but allows to return better result if position is near bitArray.length().)

The maxAvailableGap argument should be a positive power of two (2k) not less than 64 (number of bits in 1 long value). In other case, it is automatically replaced with the maximal power of two less than it (Integer.highestOneBit(maxAvailableGap)) at the very beginning of the calculations. If maxAvailableGap=0, this method always returns 0.

This method is convenient in the following typical situation. Let we have some work long[] array and we need to load there n packed bits from BitArray from the given position. The simple call getBits(position, workArray, 0, n) will work slowly if the position in the bit arrays is not aligned. But we may create a little "gap" at the beginning of the work array (so the array length should be enough to store gap+n bits). Good values for such gap is 64 or, maybe, 256 bits (1 or 4 long elements). This method allows to find the best offset withing 0..gap-1 range:

 long ofs = goodStartOffsetInArrayOfLongs(bitArray, position, 256);
 getBits(position, workArray, ofs, n);
 // processing packed bits #ofs..#ofs+n-1 in workArray
 

We recommend to use 256 bits (or large powers of two) for the gap at the beginning of the work array. Maybe, some implementations of BitArray will use alignment per 256 or more bits and will provide the best performance for aligned data blocks.

Parameters:
bitArray - the bit array
position - the index inside this bit array where you need to read or write packed bits.
maxAvailableGap - the little free starting area (number of free bits) in some long[] Java array, usually 128 or 256.
Returns:
the offset (index of a bit) in this long[] array inside 0..maxAvailableGap-1 range, providing the best speed of accessing bits via getBits(position, destArray, offset, someCount) and setBits(position, srcArray, offset, someCount) methods.
Throws:
java.lang.NullPointerException - if bitArray argument is null.
java.lang.IllegalArgumentException - if maxAvailableGap argument is negative.

insertBit

public static void insertBit(MutableBitArray array,
                             long index,
                             boolean value)
Inserts the specified boolean value at the specified position in the bit array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertBit method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertBit method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.setBit(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified bit is to be inserted.
value - bit to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertChar

public static void insertChar(MutableCharArray array,
                              long index,
                              char value)
Inserts the specified char value at the specified position in the char array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertChar method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertChar method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.setChar(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified char is to be inserted.
value - char to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertInt

public static void insertInt(MutablePIntegerArray array,
                             long index,
                             int value)
Inserts the specified int value at the specified position in the int array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertInt method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertInt method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.setInt(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified int is to be inserted.
value - int to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertLong

public static void insertLong(MutablePIntegerArray array,
                              long index,
                              long value)
Inserts the specified long value at the specified position in the long array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertLong method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertLong method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.setLong(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified long is to be inserted.
value - long to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertDouble

public static void insertDouble(MutablePFloatingArray array,
                                long index,
                                double value)
Inserts the specified double value at the specified position in the double array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertDouble method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertDouble method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.setDouble(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified double is to be inserted.
value - double to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertObject

public static <E> void insertObject(MutableObjectArray<E> array,
                                    long index,
                                    E value)
Inserts the specified Object value at the specified position in the object array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds 1 to their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (index < 0)
     throw new IndexOutOfBoundsException("Negative index (" + index + ") in insertObject method");
 if (index > len)
     throw new IndexOutOfBoundsException("Index (" +index + ") > length (" + len
         + ") in insertObject method");
 Arrays.lengthUnsigned(array, len + 1);
 array.copy(index + 1, index, len - index);
 array.set(index, value);
 

Parameters:
array - an array where you need to insert element.
index - index at which the specified object is to be inserted.
value - object to be inserted.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal index value.

insertEmptyRange

public static void insertEmptyRange(MutableArray array,
                                    long position,
                                    long count)
Increase the array length by count and shifts all elements starting from position to the right (adds count to their indexes). Elements #position..#position+count-1 are not changed. You may assign new values to these elements after calling this method with help of setData(position, someArray) or another methods.

This method is equivalent to the following operators:

 long len = array.length();
 if (position < 0)
     throw new IndexOutOfBoundsException("Negative position (" + position + ") in insertEmptyRange method");
 if (count < 0)
     throw new IndexOutOfBoundsException("Negative number of elements (" + count
         + ") in insertEmptyRange method");
 Arrays.lengthUnsigned(array, len + count);
 array.copy(position + count, position, len - position);
 

Parameters:
array - an array where you need to insert count elements.
position - start position (inclusive) of the inserted elements.
count - number of elements that you want to insert.
Throws:
java.lang.NullPointerException - if array argument is null.

remove

public static void remove(MutableArray array,
                          long position)
Removes 1 element at the specified position in the array. Shifts any subsequent elements to the left (subtracts 1 from their indexes).

This method is equivalent to the following call:

 Arrays.removeRange(array, position, 1);
 

Parameters:
array - an array where to remove element.
position - index of removed element.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal position value.

removeRange

public static void removeRange(MutableArray array,
                               long position,
                               long count)
Removes all elements at positions position..position+count-1 in the array. Shifts any subsequent elements to the left (subtracts count from their indexes).

This method is equivalent to the following operators:

 long len = array.length();
 if (position < 0)
     throw new IndexOutOfBoundsException("Negative position (" + position + ") in removeRange method");
 if (count < 0)
     throw new IndexOutOfBoundsException("Negative number of elements (" + count + ") in removeRange method");
 if (position + count > len)
     throw new IndexOutOfBoundsException("High index (" + (position + count - 1) + ") >= length (" + len
         + ") in removeRange method");
 array.copy(position, position + count, len - (position + count));
 array.length(len - count);
 

Parameters:
array - an array where to remove elements.
position - start position (inclusive) of the removed range.
count - number of removed elements.
Throws:
java.lang.NullPointerException - if array argument is null.
java.lang.IndexOutOfBoundsException - for illegal position and count (position < 0 || count < 0 || position + count > length).

sort

public static void sort(UpdatableArray array,
                        ArrayComparator comparator)
Sorts the array in increasing order, according to passed comparator. This method is equivalent to the following call:
 ArraySorter.getQuickSorter().sort(0, array.length(), comparator, array);
 
But for a case of UpdatableBitArray, this method uses more efficient algorithm.

Parameters:
array - the sorted array.
comparator - defines the order of sorted elements.
Throws:
java.lang.NullPointerException - if one of the arguments is null.

normalOrderComparator

public static ArrayComparator normalOrderComparator(UpdatableArray array)
Returns comparator allowing to sort the array in normal (increasing) order via sort method. For non-primitive arrays, the returned comparator will use standard Comparable interface (all objects must implement this interface).

Parameters:
array - the array for sorting.
Returns:
the comparator for sorting the array in increasing order.
Throws:
java.lang.NullPointerException - if array argument is null.

reverseOrderComparator

public static ArrayComparator reverseOrderComparator(UpdatableArray array)
Returns comparator allowing to sort the array in reverse (decreasing) order via sort method. For non-primitive arrays, the returned comparator will use standard Comparable interface (all objects must implement this interface).

Parameters:
array - the array for sorting.
Returns:
the comparator for sorting the array in increasing order.
Throws:
java.lang.NullPointerException - if array argument is null.

asCharSequence

public static java.lang.CharSequence asCharSequence(CharArray charArray)
Returns a view of the character array implementing standard CharSequence interface. The methods of the returned view do the following:

Please note that toString() method of CharArray returns another result, according to the common contract specified for Array.toString() method. It is the reason why CharArray cannot implement CharSequence interface itself.

Parameters:
charArray - the AlgART character array.
Returns:
CharSequence view of this character array.
Throws:
java.lang.NullPointerException - if charArray argument is null.

asList

public static <E> java.util.List<E> asList(Array array,
                                           java.lang.Class<E> listElementType)
Returns a list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between AlgART-array-based and collection-based APIs, together with Collection.toArray and SimpleMemoryModel.asUpdatableArray(Object). The returned list is serializable and implements RandomAccess.

The generic type of the list elements is listElementType. It must be the same class as, superclass of or superinterface of array.elementType(). If the array element type is primitive, the passed listElementType must be the corresponding wrapped class or its superclass, for example, Object.class.

If the passed array is PArray, all primitive elements will be automatically converted to/from the corresponding wrappers (Boolean, Byte, etc.).

The returned list will resize if the source array will resize. However, the resizing methods of the returned list will throw UnsupportedOperationException.

The returned list will be immutable if the source array does not implement UpdatableArray interface. In this case, all modification methods of the returned list will throw UnsupportedOperationException.

Parameters:
array - the AlgART array by which the list will be backed.
listElementType - the generic element type in the returned list.
Returns:
a list view of this AlgART array.
Throws:
java.lang.NullPointerException - if one of the arguments is null.
java.lang.ClassCastException - if not listElementType.isAssignableFrom(arrayElementType), where arrayElementType is array.elementType() or, for a case of primitive type, its wrapper class.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE (also thrown by List methods, if the array length will exceed this threshold later).
See Also:
SimpleMemoryModel.asUpdatableArray(Object)

asList

public static <E> java.util.List<E> asList(ObjectArray<E> array)
Equivalent to asList(array, array.elementType()}.

Parameters:
array - the AlgART array by which the list will be backed.
Returns:
a list view of this AlgART array.
Throws:
java.lang.NullPointerException - if the argument is null.
TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE (also thrown by List methods, if the array length will exceed this threshold later).

read

public static void read(java.io.InputStream inputStream,
                        UpdatablePArray array,
                        java.nio.ByteOrder byteOrder)
                 throws java.io.IOException
Reads all elements of the passed array from the passed input stream from its current position.

More precisely, this method reads sizeOf(array) bytes from the input stream (starting from the current position) by necessary number of sequential calls of dataInputStream.readFully(byteArray,0,len), where dataInputStream = new DataInputStream(inputStream) (this object is created in the beginning with the only purpose to provide readFully functionality). Then all read bytes are converted (packed) to Java array packedArray: it is long[], char[], byte[], short[], int[], long[], float[], double[], if the array is correspondingly BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray (if the array is already ByteArray, the read byte array is used without conversion). This conversion is performed according the specified byte order, like in ByteBuffer.asXxxBuffer methods (after byteBuffer.order(byteOrder) call). After this, the converted elements are sequentially written to the specified AlgART array, from its element #0 to its last element #array.length()-1, by sequential calls of setBits(position,packedArray,0,count) in a case of BitArray or setData(position,packedArray,0,count) in other cases.

Note that this method always reads from the stream the integer number of blocks per 8, 2, 1, 2, 4, 8, 4, 8 bytes for cases of (correspondingly) BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray. The total number of read bytes is sizeOf(array). If there is no such number of available bytes in the input stream, EOFException is thrown.

This method does not close the passed stream.

Parameters:
inputStream - the input stream.
array - the updatable array the should be read.
byteOrder - the byte order in the stream; it is not used in the only case of ByteArray.
Throws:
java.lang.NullPointerException - if inputStream, array or byteOrder argument is null.
java.io.IOException - in the same situations as in the standard DataInputStream.readFully method.
See Also:
write(OutputStream, PArray, ByteOrder)

write

public static void write(java.io.OutputStream outputStream,
                         PArray array,
                         java.nio.ByteOrder byteOrder)
                  throws java.io.IOException
Writes all elements of the passed array to the passed output stream from its current position.

More precisely, this method writes sizeOf(array) bytes to the output stream (starting from the current position) by necessary number of sequential calls of outputStream.write(byteArray,0,len). The necessary byte array byteArray is built by conversion (unpacking) of the Java array packedArray, read from the sequential ranges of the array: it is long[], char[], byte[], short[], int[], long[], float[], double[], if the array is correspondingly BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray (if the array is already ByteArray, the read byte array is used without conversion). This conversion is performed according the specified byte order, like in ByteBuffer.asXxxBuffer methods (after byteBuffer.order(byteOrder) call). The packedArray is sequentially read from the specified AlgART array, from its element #0 to its last element #array.length()-1, by sequential calls of getBits(position,packedArray,0,count) in a case of BitArray or getData(position,packedArray,0,count) in other cases.

Note that this method always writes in the stream the integer number of blocks per 8, 2, 1, 2, 4, 8, 4, 8 bytes for cases of (correspondingly) BitArray, CharArray, ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray. The total number of written bytes is sizeOf(array). If the array is BitArray and its length n=array.length() is not divisible by 64, then the last unused r=64−(n%64) bits in the last long value are filled by zero. (These last r unused bits, in a case of little-endian byte order, are stored in the last (r+7)/8 bytes of the output stream; in a case of big-endian byte order they are stored in the first (r+7)/8 bytes of the last 8-byte block.)

This method does not flush or close the passed stream.

Parameters:
outputStream - the output stream.
array - the array the should be written.
byteOrder - the byte order in the stream; it is not used in the only case of ByteArray.
Throws:
java.lang.NullPointerException - if outputStream, array or byteOrder argument is null.
java.io.IOException - in the same situations as in the standard OutputStream.write method.
See Also:
read(InputStream, UpdatablePArray, ByteOrder)

getUnderlyingArrays

public static Array[] getUnderlyingArrays(Array array)
Returns Java array of the underlying AlgART arrays of the given AlgART array.

More precisely, lets Array[] underlyingArrays are the following arrays:

  1. all arrays passed to method, if the array argument was constructed by one of those methods;
  2. the underlying array of the matrix (matrix.array()), if the array argument the underlying array of its submatrix, created by one of its subMatrix or subMatr methods, for example: array=matrix.subMatrix(from,to).array();
  3. the underlyingArrays argument of the constructor of this class or the constructor of the AbstractArray inheritors from this package (as AbstractByteArray, AbstractUpdatableByteArray, AbstractCharArray, AbstractUpdatableCharArray, etc.), if the array argument was created by one of that constructor in the custom subclass of that classes;
  4. the underlying arrays, specified in positions 1–3, of some parent AlgART array, if the array argument is a view of that parent array created by Array.subArray(long, long), Array.subArr(long, long) or Array.asImmutable() methods. (Please draw attention: there is no way to get the "parent" array, if we have its subarray: this method returns the underlying arrays of the parent instead. An array and its subarrays are considered to be peer: the containing array has no advantages over its subarrays.)

Then the result of this method consists of arrays, produced by operators underlyingArrays[k].asImmutable(), if the passed array is immutable, or underlyingArrays[k].shallowClone() in other cases.

If the passed array is not created by one of the ways listed above, this method returns the empty Array[0] Java array. This method never returns null.

Parameters:
array - the checked AlgART array.
Returns:
Java array of immutable views / shallow copies of its underlying arrays.
Throws:
java.lang.NullPointerException - if array argument is null.
See Also:
getUnderlyingArraysNewStatus(Array)

getUnderlyingArraysNewStatus

public static boolean[] getUnderlyingArraysNewStatus(Array array)
Returns boolean[] array, containing underlyingArrays[k].isNew() values, for all underlying arrays of the passed one. Please see getUnderlyingArrays(Array) method to clarify the precise sense of "underlying arrays" term. This method is necessary in addition to getUnderlyingArrays(Array), because the arrays, returned by that method, are always non-new (they are produced by Array.asImmutable() method, which returns not a new array, but a view of an array).

If the passed array has no underlying arrays, that can be recognized by this package, this method returns the empty boolean[0] Java array. This method never returns null.

Note: we do not need an analogous method for getting underlyingArrays[k].isNewReadOnlyView() values, because Array.asImmutable() method always preserves the new-read-only-view status (see the last note in the comments to Array.asImmutable()).

Parameters:
array - the checked AlgART array.
Returns:
Java array of "new" statuses of all its underlying arrays.
Throws:
java.lang.NullPointerException - if array argument is null.

getUnderlyingArraysCount

public static int getUnderlyingArraysCount(Array array)
Returns the number of the underlying AlgART arrays of the given AlgART array. Please see getUnderlyingArrays(Array) method to clarify the precise sense of "underlying arrays" term. This method is useful in addition to getUnderlyingArrays(Array), because it does not allocate any memory and works very quickly.

If the passed array has no underlying arrays, that can be recognized by this package, this method returns 0.

Parameters:
array - the checked AlgART array.
Returns:
the number of the underlying AlgART arrays of the given AlgART array.
Throws:
java.lang.NullPointerException - if array argument is null.

longMul

public static long longMul(long[] multipliers,
                           int from,
                           int to)
Returns the product of passed multipliers from the index, specified in from argument (inclusive), until the index, specified in to argument (exclusive), i.e. multipliers[from]*multipliers[from+1]*...*multipliers[to-1], if this product is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow").

Must be 0<=from<=to<=multipliers.length. If from==to, returns 1.

Note: if the product is Long.MIN_VALUE, this situation cannot be distinguished from the overflow.

Also note: if at least one of the passed multipliers is 0, then the result will be always 0, even if product of some other multipliers is out of -263+1..263-1 range.

Parameters:
multipliers - the long values to be multiplied.
from - the initial index in array, inclusive.
to - the end index in array, exclusive.
Returns:
the product of all multipliers or Long.MIN_VALUE if a case of overflow.
Throws:
java.lang.NullPointerException - if multipliers argument is null.
java.lang.IndexOutOfBoundsException - if from<0 or to>multipliers.length.
java.lang.IllegalArgumentException - if from>to.
See Also:
longMul(long...), longMul(long, long)

longMul

public static long longMul(long... multipliers)
Returns the product of all passed multipliers (multipliers[0]*multipliers[1]*...), if it is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow"). Equivalent to longMul(multipliers,0,multipliers.length).

If the multipliers array is empty (longMul() call), returns 1.

Note: if the product is Long.MIN_VALUE, this situation cannot be distinguished from the overflow.

Also note: if at least one of the passed multipliers is 0, then the result will be always 0, even if product of some other multipliers is out of -263+1..263-1 range.

Parameters:
multipliers - the long values to be multiplied.
Returns:
the product of all multipliers or Long.MIN_VALUE if a case of overflow.
Throws:
java.lang.NullPointerException - if multipliers argument is null.
See Also:
longMul(long[], int, int), longMul(long, long)

longMul

public static long longMul(long a,
                           long b)
Returns the product a*b, if it is in -263+1..263-1 range, or Long.MIN_VALUE (-263) in other cases ("overflow").

Note: if the product is Long.MIN_VALUE, this situation cannot be distinguished from the overflow.

Also note: if one of the multipliers a and b is equal to the "overflow marker" Long.MIN_VALUE, then, as it is follows from the common rule, the result of this method will also be equal to Long.MIN_VALUE — excepting the only case, when one of the multipliers a and b is zero. If a==0 or b==0, the result is always 0.

Parameters:
a - the first long value.
b - the second long value.
Returns:
the product a*b or Long.MIN_VALUE if a case of overflow.
See Also:
longMul(long...), longMul(long[], int, int)

compactCyclicPositions

public static long compactCyclicPositions(long length,
                                          long[] positions)
Finds the shortest cyclic range, containing all passed positions in the cyclic range 0..length-1, returns the beginning of this range as the method result, cyclically subtracts it from all elements of the passed array and returns the sorted array of resulting positions in the positions argument.

More precisely, let positions argument contains any numbers from 0 to length-1. Let's consider the circle with length, equal to the length argument (with length/π diameter). Let pk is the point at this circle, corresponding to position[k], i.e. such point that the (anticlockwise) arc from the rightmost point P = (length/2π,0) of the circle to pk has the length equal to position[k]. (For typical applications of this method, all points are relatively compact group at the circle, usually near the starting P point.)

This method finds the shortest (anticlockwise) arc (pipj), that contains all other points. The start of the found arc, that is the length of (anticlockwise) arc (Ppi)=positions[i], will be the result of the method. Then this method rotates all points clockwise by this value, so that the pi is moved to the starting point P. (In other words, it replaces every positions[k] with positions[k]-sh>=0 ? positions[k]-sh : positions[k]-sh+length, where sh=positions[i] is the result of this method.) At last, the method sorts the positions by increasing (i.e. sorts points anticlockwise). The sorted array is returned in positions argument.

If positions.length==0 (empty array), this method returns 0 and does nothing. If positions.length==1 (1 point at the cirlce), this method sets positions[0]=0 and returns the previous value of positions[0]. If length==0 or length<0, this method throws IllegalArgumentException: such length is not allowed.

This method is used by some algorithms processing several AlgART arrays, cyclically shifted by asShifted(Array, long) or similar method. In this case, the length argument corresponds to the array length, and positions correspond to the shifts of all arrays.

Parameters:
length - the length of the cycle (circle).
positions - some positions inside 0..length-1 range; they will be corrected by this method: elements are sorted by increasing, and some element (retuned as the result) is cyclically subtracted from all other elements, to provide the minimal value of the maximal element.
Returns:
the value of the element of the original positions array, which is the start of the shortest cyclic range arc.
Throws:
java.lang.NullPointerException - if positions argument is null.
java.lang.IllegalArgumentException - if length<=0, or if some of passed positions are not in 0..length-1 range.

getThreadPoolFactory

public static ThreadPoolFactory getThreadPoolFactory(ArrayContext context)
Returns context.getThreadPoolFactory() if context!=null or DefaultThreadPoolFactory.getDefaultThreadPoolFactory() if context==null. It is the most typical way to get new thread pool factory for processing AlgART arrays.

Parameters:
context - some array context; may be null.
Returns:
the thread pool factory, provided by this context, or the default thread pool factory if the argument is null.

freeAllResources

public static void freeAllResources()
Releases all resources, associated with any AlgART arrays created by this package. Almost equivalent to calling freeResources(null) method for all arrays that were used in the application since its start (including arrays that are in finalization stage). The only difference is that this method, unlike freeResources(null), does not provide flushing guarantees 1 and 2, described in comments to flushResources method: in particular, some array data may still be not stored in external resources, if it requires essential time. The only purpose of this method is freeing occupied resources, not providing guarantees concerning flushing data at this moment.

The same actions are automatically performed while built-in cleanup procedure called while shutdown hook installed by this package. However, these actions may require a long time, if freeResources method was not accurately called after every usage of AlgART arrays. It may extremely slow down JVM termination. To avoid this effect, you may call this method after any large calculation stage, in particular, in closing dialog of your application.

On the other hand, built-in cleanup procedure may work essentially faster than this method. The reason is that all non-finalized arrays must stay alive after this method: the next access to them must reload their data from external devices. So, this method must save all data on external devices while releasing resources. Unlike this, the built-in cleanup procedure has a right to lose any data in temporary created resources. As an alternate, you may use gcAndAwaitFinalization(int) method.

This method is thread-safe and can be executed in a parallel thread.


gcAndAwaitFinalization

public static boolean gcAndAwaitFinalization(int timeoutInMilliseconds)
                                      throws java.lang.InterruptedException
Performs a loop of System.runFinalization() and System.gc(), and waits for finishing all finalization tasks that are scheduled by any classes of this package. Does nothing if there are no scheduled finalization tasks. Doesn't wait more than the specified number milliseconds. Returns true if all finalization tasks were successfully completed or false in a case of timeout.

Warning: you must never call this method it there is at least one strongly or softly reachable AlgART array instance, that was not released by Array.freeResources method. If you call this method in such situation, it's possible that the method will wait for the specified timeout and return false.

We don't recommend to call this method without necessity: it can require essential time and clear all existing caches based on weak references. Moreover, there is no guarantee that finalization tasks will be performed at all (in particular, if there are some strongly or softly reachable AlgART arrays). So, not too large timeoutInMilliseconds argument is absolutely necessary. As an alternate, you may use freeAllResources() method.

You may call this method at the end of the application or at the end of large module to avoid leaving extra temporary files and leak of disk space. Though the same cleanup procedures are performed in the standard shutdown hook installed by this package, but this method increases the probability that all extra resources will be really removed.

In current implementation, only creation arrays by the large memory model schedules some tasks: namely, automatic releasing used resources and deletion of temporary files.

Parameters:
timeoutInMilliseconds - the maximal time to wait in milliseconds; please not specify large values here: several seconds is a good choice.
Returns:
true if all finalization tasks were successfully completed.
Throws:
java.lang.IllegalArgumentException - if timeoutInMilliseconds <= 0.
java.lang.InterruptedException - if another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

throwException

public static <T extends java.lang.Exception> void throwException(java.lang.Class<? extends T> exceptionClass,
                                                                  java.lang.Throwable exception)
                           throws T extends java.lang.Exception
Throws the specified exception, supposed to be unchecked or belonging to the specified class — in other words, throws the argument, if it is RuntimeException, Error or an instance of exceptionClass. In other cases, this method throws AssertionError.

The implementation of this method is strictly following:

 if (exceptionClass.isInstance(exception)) {
     throw exceptionClass.cast(exception);
 }
 if (exception instanceof RuntimeException) {
     throw (RuntimeException) exception;
 }
 if (exception instanceof Error) {
     throw (Error) exception;
 }
 throw new AssertionError("Impossible exception: " + exception);
 

This method is convenient when you need to catch all exceptions of the specified class and also all unchecked exceptions and errors, then do something in connection with an exception/error, and then re-throw the exception/error. For example:

 try {
     // creating some work files for storing large data
     // (IOException, IOError or some unexpected RuntimeException are possible)
 } catch (Throwable e) {
     dispose();
     // - this method removes all previously created work files
     Arrays.throwException(IOException.class, e);
 }
 

You must be sure that the Throwable argument of this method is really RuntimeException, Error or an instance of exceptionClass — all other exceptions are also caught by this method, but lead to throwing AssertionError.

Parameters:
exceptionClass - the class all checked exceptions, that can appear in the 2nd argument.
exception - some exception of the specified class or unchecked exception.
Throws:
T extends java.lang.Exception

throwUncheckedException

public static void throwUncheckedException(java.lang.Throwable exception)
Throws the specified unchecked exception — in other words, throws the argument, if it is RuntimeException or Error. In other cases, this method throws AssertionError.

The implementation of this method is strictly following:

 if (exception instanceof RuntimeException) {
     throw (RuntimeException) exception;
 }
 if (exception instanceof Error) {
     throw (Error) exception;
 }
 throw new AssertionError("Impossible checked exception: " + exception);
 

This method is convenient when you need to catch all unchecked exceptions and errors, then do something in connection with an exception/error, and then re-throw the exception/error. For example:

 try {
     // some your code
 } catch (Throwable e) {
     exceptionOccurred = true;
     // - fix in some field "exceptionOccurred" the fact, that there were some exceptions
     Arrays.throwUncheckedException(e);
 }
 

You must be sure that the Throwable argument of this method is really RuntimeException or Error — all other exceptions are also caught by this method, but lead to throwing AssertionError.

Parameters:
exception - some unchecked exception.

addShutdownTask

public static void addShutdownTask(java.lang.Runnable task,
                                   Arrays.TaskExecutionOrder whenToExecute)
Schedules the given task to be performed while system shutting down.

This package automatically registers one virtual-machine shutdown hook by standard Runtime.getRuntime().addShutdownHook(...) call. This hook performs all tasks, passed to this method, in strict order specified below (unlike hooks registered by addShutdownHook).

  1. First of all, all tasks, passed to this method with the second argument equal to Arrays.TaskExecutionOrder.BEFORE_STANDARD, are performed, in the same order as calls of this method.
  2. Then the standard finalization tasks, provided by this package, are performed. In particular, it includes deletion of all files returned by DataFileModel.allTemporaryFiles() method for all data file models, used since the application start. As a result, most of or (if there were no file blocking problems) all these temporary files are removed.
  3. In fine, all tasks, passed to this method with the second argument equal to Arrays.TaskExecutionOrder.AFTER_STANDARD, are performed, in the same order as calls of this method.

In the 3rd step, the DataFileModel.allTemporaryFiles() method returns only data files that were not successfully deleted in the 2nd step due to some problems (usually, because of impossibility of deleting mapped file before the garbage collector will finalize all MappedByteBuffer instances). So, it is a good idea to schedule here a task that will save paths to all these non-deleted files in some text log. (You may use LargeMemoryModel.allUsedDataFileModelsWithAutoDeletion() method to get a collection of all used data file models.) While the next application start, it will be able to remove all these files.

The tasks scheduled by this method should not throw any exceptions. If some exception is still thrown, the stack trace is printed to the system console (by printStackTrace() method) and the further tasks are executed: an exception does not break all shutdown hook.

Parameters:
task - the scheduled task (its run() method will be called).
whenToExecute - when to call the task: before or after standard ones.
Throws:
java.lang.NullPointerException - if task or whenToExecute is null.