Class Arrays

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

public class Arrays extends Object

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

This class cannot be instantiated.

Author:
Daniel Alievsky
  • Field Details

  • Method Details

    • elementType

      public static Class<?> elementType(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:
      NullPointerException - if the passed argument is null.
      IllegalArgumentException - if the passed argument is not a class of primitive array.
      See Also:
    • type

      public static <T extends Array> Class<T> type(Class<T> arraySupertype, 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:
      NullPointerException - if one of the passed arguments is null.
      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(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(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(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(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(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(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(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(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(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:
      NullPointerException - if the argument is null.
      See Also:
    • sizeOf

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

      More precisely:

      • for boolean.class, returns 8*PackedBitArrays.packedLength(arrayLength) (8 is the number of bytes in one long value);
      • for char.class, returns 2*arrayLength;
      • for byte.class, returns arrayLength;
      • for short.class, returns 2*arrayLength;
      • for int.class, returns 4*arrayLength;
      • for long.class, returns 8*arrayLength;
      • for float.class, returns 4*arrayLength;
      • for double.class, returns 8*arrayLength;
      • for all other cases, returns -1 ("unknown size").

      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

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

      More precisely:

      • for boolean.class, returns 0.125 (1/8);
      • for char.class, returns 2;
      • for byte.class, returns 1;
      • for short.class, returns 2;
      • for int.class, returns 4;
      • for long.class, returns 8;
      • for float.class, returns 4;
      • for double.class, returns 8;
      • for all other cases, returns -1 ("unknown size").
      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:
    • bitsPerElement

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

      More precisely:

      • for boolean.class, returns 1;
      • for char.class, returns 16;
      • for byte.class, returns 8;
      • for short.class, returns 16;
      • for int.class, returns 32;
      • for long.class, returns 64;
      • for float.class, returns 32;
      • for double.class, returns 64;
      • for all other cases, returns -1 ("unknown size").
      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:
    • isFloatingPointElementType

      public static boolean isFloatingPointElementType(Class<?> elementType)
      Returns true if the passed element type is float.class or double.class.
      Parameters:
      elementType - some primitive element type; may be null, then false is returned.
      Returns:
      whether this element type is a floating-point primitive type.
    • isUnsignedElementType

      public static boolean isUnsignedElementType(Class<?> elementType)
      Returns true if the passed element type is boolean.class, short.class, byte.class or short.class.
      Parameters:
      elementType - some primitive element type; may be null, then false is returned.
      Returns:
      whether this element type should be interpreted as unsigned primitive type.
    • minPossibleIntegerValue

      public static long minPossibleIntegerValue(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:
      • 0 for BitArray.class (and its inheritors),
      • 0 for CharArray.class (and its inheritors),
      • 0 for ByteArray.class (and its inheritors),
      • 0 for ShortArray.class (and its inheritors),
      • Integer.MIN_VALUE for IntArray.class (and its inheritors),
      • Long.MIN_VALUE for LongArray.class (and its inheritors).
      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:
      NullPointerException - if the passed argument is null.
      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:
    • maxPossibleIntegerValue

      public static long maxPossibleIntegerValue(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:
      • 1 for BitArray.class (and its inheritors),
      • 0xFFFF for CharArray.class (and its inheritors),
      • 0xFF for ByteArray.class (and its inheritors),
      • 0xFFFF for ShortArray.class (and its inheritors),
      • Integer.MAX_VALUE for IntArray.class (and its inheritors),
      • Long.MAX_VALUE for LongArray.class (and its inheritors).
      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:
      NullPointerException - if the passed argument is null.
      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:
    • minPossibleValue

      public static double minPossibleValue(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:
      NullPointerException - if the passed arrayType is null.
      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:
    • maxPossibleValue

      public static double maxPossibleValue(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:
      NullPointerException - if the passed arrayType is null.
      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:
    • minPossibleValue

      public static double minPossibleValue(Class<? extends Array> arrayType)
      Returns minPossibleValue(arrayType, 0.0). It is a good default for most application.
      Parameters:
      arrayType - the type of some AlgART array.
      Returns:
      the minimal possible value, that can be stored in such fixed-point primitive arrays, or 0.0 for other array types.
      Throws:
      NullPointerException - if the passed arrayType is null.
      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.
    • maxPossibleValue

      public static double maxPossibleValue(Class<? extends Array> arrayType)
      Returns minPossibleValue(arrayType, 1.0). It is a good default for most application.
      Parameters:
      arrayType - the type of some AlgART array.
      Returns:
      the maximal possible value, that can be stored in such fixed-point primitive arrays, or 1.0 for other array types.
      Throws:
      NullPointerException - if the passed arrayType is null.
      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:
    • 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:
      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:
      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:
      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:
      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:
      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:
      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:
      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:
      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:
      IllegalArgumentException - if n < 0.
    • nPCopies

      public static PArray nPCopies(long n, 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:
      • nBitCopies(n, element != 0) if elementType==boolean.class,
      • nCharCopies(n, (char)element) if elementType==char.class,
      • nByteCopies(n, (byte)element) if elementType==byte.class,
      • nShortCopies(n, (short)element) if elementType==short.class,
      • nIntCopies(n, (int)element) if elementType==int.class,
      • nLongCopies(n, (long)element) if elementType==long.class,
      • nFloatCopies(n, (float)element) if elementType==float.class or
      • nDoubleCopies(n, element) if elementType==double.class.
      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:
      NullPointerException - if elementType is null.
      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, 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:
      • nBitCopies(n, element != 0) if elementType==boolean.class,
      • nCharCopies(n, (char)element) if elementType==char.class,
      • nByteCopies(n, (byte)element) if elementType==byte.class,
      • nShortCopies(n, (short)element) if elementType==short.class,
      • nIntCopies(n, (int)element) if elementType==int.class or
      • nLongCopies(n, element) if elementType==long.class.
      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:
      NullPointerException - if elementType is null.
      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, 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:
      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, Class<? extends T> requiredType, long 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:
      NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
      IllegalArgumentException - in the same situations as asIndexFuncArray(boolean, Func, Class, long) method.
    • asIndexFuncArray

      public static <T extends PArray> T asIndexFuncArray(boolean truncateOverflows, Func f, 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:
      NullPointerException - if f or requiredType argument is null.
      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, Class<? extends T> requiredType, PArray... 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:
      NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
      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, 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 simplest case is when the required type is DoubleArray: then w=v.
      • If the required type is FloatArray, then w=(float)v.
      • If the required type is IntArray, ShortArray, ByteArray or CharArray, then the behavior depends on the truncateOverflows argument.
        • If truncateOverflows is false: (ByteArray and ShortArray are considered to be unsigned.) In other words, v is cast to the maximally "wide" long type and then the low 32, 16 or 8 bits of this long value are extracted.
        • If truncateOverflows is true:
          • w=(int)v for IntArray,
          • w=(int)v<0?0:(int)v>0xFFFF?0xFFFF:(int)v for ShortArray,
          • w=(int)v<0?0:(int)v>0xFF?0xFF:(int)v for ByteArray,
          • w=(int)v<0?0:(int)v>0xFFFF?0xFFFF:(char)(int)v for CharArray.
          In other words, v is truncated to the allowed range and then cast to the required integer type.
      • If the required type is LongArray, then w=(long)v. According the Java specification, it means v, truncated to long value, if Long.MIN_VALUE<=v<=Long.MAX_VALUE, or the nearest from Long.MIN_VALUE / Long.MAX_VALUE if v is out of this range. In comparison with other integer types, it's possible to say that the truncateOverflows argument is always supposed to be true.
      • If the required type is BitArray, then w=true if v!=0.0 or w=false if v==0.0 (C-like agreement).

      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:

      • every data block (sequence of elements) is first fully calculated (on the base the underlying arrays, via the passed function);
      • then it is returned to the client (loaded into Java array, copied into another AlgART array, etc.): the result of accessing method is never modified before the data block is completely calculated;
      • if there are several calculated data blocks, then the blocks with less indexes of elements are always processed before blocks with greater indexes.

      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:
      NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
      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

      public static <T extends UpdatablePArray> T asUpdatableFuncArray(Func.Updatable f, Class<? extends T> requiredType, UpdatablePArray... 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:
      NullPointerException - if requiredType or x argument is null or if one of x arrays is null.
      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, 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:
      NullPointerException - if f or requiredType argument is null or if one of x arrays is null.
      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:
    • applyFunc

      public static void applyFunc(ArrayContext context, Func f, UpdatablePArray result, PArray... 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:
      NullPointerException - if f, result, x or one of x arrays is null.
      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.
      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)
      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:
      NullPointerException - if f, result, x or one of x arrays is null.
      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.
      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:
      NullPointerException - if f, result, x or one of x arrays is null.
      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.
      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:
      • asCoordFuncMatrix,
      • asFuncMatrix,
      • asUpdatableFuncMatrix.
      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

      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:
    • 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:
      NullPointerException - if the argument is null.
      IllegalArgumentException - if the passed array is not functional, i.e. if isFuncArray(Array) returns false for it.
      See Also:
    • 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:
      NullPointerException - if the argument is null.
      IllegalArgumentException - if the passed array is not functional, i.e. if isFuncArray(Array) returns false for it.
      See Also:
    • 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:
      NullPointerException - if the argument is null.
      IllegalArgumentException - if the passed array is not index-based functional, i.e. if isIndexFuncArray(Array) returns false for it.
      See Also:
    • 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:
      NullPointerException - if arrays argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if the argument is null.
      IllegalArgumentException - if the passed array is not shifted, i.e. if isShifted(Array) returns false for it.
      See Also:
    • 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:
      NullPointerException - if src or dest argument is null.
      IllegalArgumentException - if the source and destination element types do not match.
      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

      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:
      NullPointerException - if src or dest argument is null.
      IllegalArgumentException - if the source and destination element types do not match, or if the numberOfThreads argument is negative.
      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

      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:
      NullPointerException - if src or dest argument is null.
      IllegalArgumentException - if the source and destination element types do not match, or if the numberOfThreads argument is negative.
      IOError - if the current thread is interrupted by the standard Thread.interrupt() call (this technique may be not supported in some cases).
      See Also:
    • 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:
      NullPointerException - if src or dest argument is null.
      IllegalArgumentException - if the source and destination element types do not match.
      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)
      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:
      NullPointerException - if array argument is null.
      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 the 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, will contain an index of the first such element. If there are several elements equal to the maximum, the index of maximum, stored in this object, may contain an index of the first 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.

      If the passed array is PFloatingArray, please note that NaN values are exlcuded from comparison: this method finds minimums and maximum among all elements, excepting NaN. If all elements of the array are NaN, it is a special case: this method returns Range.valueOf(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY). You can detect this situation with help of allNaN() method of minMaxInfo argument.

      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:
      NullPointerException - if array argument is null.
      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)
      Parameters:
      array - some primitive array.
      Returns:
      the values of the found minimal and maximal elements.
      Throws:
      NullPointerException - if array argument is null.
      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)
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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.

      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:
      NullPointerException - if array argument is null.
      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 ArithmeticException
      Parameters:
      array - some primitive array, excluding floating point arrays.
      checkOverflow - whether overflow should lead to ArithmeticException
      Returns:
      the sum of all array elements.
      Throws:
      NullPointerException - if array argument is null.
      ArithmeticException - if checkOverflow is true and the result or some partial sum cannot be represented by long value.
      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 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:
      NullPointerException - if array argument is null.
      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)
      Parameters:
      array - some primitive array, excluding floating point arrays.
      Returns:
      the sum of all array elements.
      Throws:
      NullPointerException - if array argument is null.
      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)
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if bitArray argument is null.
      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:
      NullPointerException - if bitArray argument is null.
      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)
      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:
      NullPointerException - if array or histogram argument is null.
      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.

      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:
      NullPointerException - if array or histogram argument is null.
      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(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • packBitsLess

      public static void packBitsLess(UpdatableBitArray bits, PArray array, double threshold)
      Equivalent to packBitsLess(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • packBitsGreaterOrEqual

      public static void packBitsGreaterOrEqual(UpdatableBitArray bits, PArray array, double threshold)
      Equivalent to packBitsGreaterOrEqual(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • packBitsLessOrEqual

      public static void packBitsLessOrEqual(UpdatableBitArray bits, PArray array, double threshold)
      Equivalent to packBitsLessOrEqual(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • unpackBits

      public static void unpackBits(UpdatablePArray array, BitArray bits, double filler0, double filler1)
      Equivalent to unpackBits(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • unpackUnitBits

      public static void unpackUnitBits(UpdatablePArray array, BitArray bits, double filler1)
      Equivalent to unpackUnitBits(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • unpackZeroBits

      public static void unpackZeroBits(UpdatablePArray array, BitArray bits, double filler0)
      Equivalent to unpackZeroBits(ArrayContext.DEFAULT_SINGLE_THREAD, 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
    • 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:
      NullPointerException - if array or bits argument is null.
      SizeMismatchException - if array.length()!=bits.length().
      See Also:
    • asPrecision

      public static PArray asPrecision(PArray array, Class<?> newElementType)
      Returns an immutable view of the passed AlgART array, cast to another primitive element type (other precision) with automatic scaling, so that 0.0 is cast to 0.0 and maximal possible value of the source array is scaled to maximal possible value of the result. (For float and double elements we suppose that maximal possible value is 1.0.)

      More precisely, if newElementType==array.elementType(), this function just returns the array argument without changes, in other case it is equivalent to the following operators:

           final Class newType = Arrays.type(PArray.class, newElementType);
           final Range destRange = Range.valueOf(0.0, Arrays.maxPossibleValue(newType));
           final Range srcRange = Range.valueOf(0.0, array.maxPossibleValue(1.0));
           return Arrays.asFuncArray(LinearFunc.getInstance(destRange, srcRange), newType, array);
       
      Parameters:
      array - the source AlgART array.
      newElementType - required element type.
      Returns:
      the array with the required element type, where every element is equal to the corresponding element of the source array, multiplied by the automatically chosen scale.
      Throws:
      NullPointerException - if one of the arguments is null.
      IllegalArgumentException - if the required element type is not a primitive type.
    • applyPrecision

      public static void applyPrecision(ArrayContext context, UpdatablePArray result, PArray array)
      Equivalent to creating a "lazy" array by lazy = asPrecision(array, result.elementType() call and copying it into the result argument by copy(context, result, lazy) call.

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

      If the source and result array have the same element type, this method just copies array to result.

      Parameters:
      context - the context of copying; may be null, then it will be ignored.
      result - the destination array.
      array - the source array.
      Throws:
      NullPointerException - if result or array is null.
      SizeMismatchException - if passed arrays have different lengths.
      IOError - if the current thread is interrupted by the standard Thread.interrupt() call.
    • 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:
      NullPointerException - if array argument is null.
      See Also:
    • copyArrayToBytes

      public static byte[] copyArrayToBytes(byte[] bytes, PArray array, ByteOrder byteOrder)
      Copies all elements of the given AlgART array (2nd argument) into the bytes Java array (1st argument, or into a newly created byte[] array if bytes==null), and returns the resulting byte[] array.

      The length of bytes array must be enough for storing all elements of the given AlgART array (but may be greater than necessary). More precisely, bytes.length must be ≥Arrays.sizeOfBytesForCopying(array). Note that Arrays.sizeOf(array) is a suitable length for all types (though for BitArray it can be little greater than necessary).

      The bytes argument may be null; in this case, this method automatically allocates byte[] array with minimal necessary length Arrays.sizeOfBytesForCopying(array), copies all elements of the AlgART array into it and returns it.

      The array element #k (array.getElement(k)) is stored at the following position in the bytes Java array:

      • for BitArray, bit #k is stored in the bit #k%8 in the byte bytes[k/8], i.e. in bytes[k/8] & (1<<(k%8)); several last unused bits of the last byte are cleared to zero (the number of these bits is 8*(N/8)-N, where N=array.length());
      • for ByteArray, byte #k is stored in the byte bytes[k];
      • for other variants of PArray, element #k is stored in bytesPerElement sequential bytes bytes[k*bytesPerElement]...bytes[k*bytesPerElement+bytesPerElement-1], where bytesPerElement is 2, 2, 4, 8, 4, 8 for an array of char, short, int, long, float, double correspondingly;
      • all elements, greater than 1 byte — char, short, int, long, float, double — are stored as sequences of 2, 2, 4, 8, 4, 8 bytes (correspondingly) according to the byte order, specified in the last argument (see java.nio.ByteOrder);
      • every float element of FloatArray is stored as a sequence of 4 bytes of int value, got by Float.floatToRawIntBits method (from lowest to highest); every double element of DoubleArray is stored as a sequence of 8 bytes of long value, got by Double.doubleToRawLongBits method (from lowest to highest).

      This method can be used for serialization of AlgART arrays into a form, suitable for writing into OutputStream, for example, for storing on external devices or passing through the network.

      Note: unlike write(OutputStream, PArray, ByteOrder) method, this method specifies the storage scheme absolutely strictly and does not depend on ByteBuffer implementation. On the other hand, serialization via this method can work little slower than write method.

      Also note: unlike write(OutputStream, PArray, ByteOrder) method, for BitArray case this method requires little less bytes: sizeOfBytesForCopying(array) instead of sizeOf(array). If you are interested in compatibility with write / read methods, you should allocate and serialize (int)Arrays.sizeOf(array) bytes instead of Arrays.sizeOfBytesForCopying(array).

      We recommend calling this method for relatively small arrays only, up to several megabytes, to avoid extra usage of RAM. If you need to serialize a large AlgART array, you may apply this method sequentially for its subarrays.

      Parameters:
      bytes - Java array, to which the content of the source array will be copied; may be null, then it will be allocated automatically
      array - the source AlgART array.
      byteOrder - the byte order for element types, greater than 1 byte; it is not used in cases of ByteArray and BitArray.
      Returns:
      Java array with resulting data; if bytes argument is not null, a reference to this argument is returned.
      Throws:
      NullPointerException - if array or byteOrder argument is null.
      TooLargeArrayException - if the required Java array length is greater than Integer.MAX_VALUE elements.
      IndexOutOfBoundsException - if bytes!=null and the length of bytes array is not enough for storing all elements of the source AlgART array.
      See Also:
    • copyBytesToArray

      public static void copyBytesToArray(UpdatablePArray array, byte[] bytes, ByteOrder byteOrder)
      Copies the elements, stored in the bytes Java array (2nd argument) by previous copyArrayToBytes(byte[], PArray, ByteOrder) call, back into the given AlgART array (1st argument).

      As in copyArrayToBytes method, the length of bytes array must be enough for storing all elements of the given AlgART array. More precisely, bytes.length must be ≥Arrays.sizeOfBytesForCopying(array). Note that Arrays.sizeOf(array) is a suitable length for all types (though for BitArray it can be little greater than necessary). This method always copies all array.length() elements of the passed array, regardless on the length of bytes array.

      The array element #k (array.getElement(k)) is retrieved from the same position in the bytes Java array, where it is stored by copyArrayToBytes(byte[], PArray, ByteOrder) method (see comments to it). The elements float and double are retrieved from the corresponding byte sequences via Float.intBitsToFloat and Double.longBitsToDouble methods.

      This method can be used for deserialization of AlgART arrays from a form, created by copyArrayToBytes method and loaded from InputStream, for example, after reading from external devices or passing through the network.

      Note: unlike read(InputStream, UpdatablePArray, ByteOrder) method, this method specify that storage algorithms absolutely strictly and does not depend on ByteBuffer implementation. On the other hand, deserialization via this method can work little slower than read method.

      We recommend calling this method for relatively small arrays only, up to several megabytes, to avoid extra usage of RAM. If you need to deserialize a large AlgART array, you may apply this method sequentially for its subarrays.

      Parameters:
      array - the target AlgART array, all elements of which should be copied from the Java array.
      bytes - the source Java array, filled according the specification of copyArrayToBytes method.
      byteOrder - the byte order for element types, greater than 1 byte; it is not used in cases of ByteArray and BitArray.
      Throws:
      NullPointerException - if any of the arguments is null.
      IndexOutOfBoundsException - if the length of bytes array is not enough for storing all elements of the target AlgART array.
      See Also:
    • sizeOfBytesForCopying

      public static int sizeOfBytesForCopying(PArray array)
      Returns the minimal size of byte[] array, enough for copying there the given AlgART array by copyArrayToBytes(byte[], PArray, ByteOrder) method. More precisely, returns array.length()+7/8 for BitArray or Arrays.sizeOf(array) for other primitive types.
      Parameters:
      array - the source AlgART array.
      Returns:
      the minimal size of byte[] array, enough for calling copyArrayToBytes(byte[], PArray, ByteOrder) method.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the result (required Java array length) is greater than Integer.MAX_VALUE elements.
    • write

      public static void write(OutputStream outputStream, PArray array, ByteOrder byteOrder) throws 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 and reading 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), excepting the case of BitArray, when ByteOrder.LITTLE_ENDIAN order is used always. 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 cases of ByteArray and BitArray.
      Throws:
      NullPointerException - if outputStream, array or byteOrder argument is null.
      IOException - in the same situations as in the standard OutputStream.write method.
      See Also:
    • read

      public static void read(InputStream inputStream, UpdatablePArray array, ByteOrder byteOrder) throws 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), excepting the case of BitArray, when ByteOrder.LITTLE_ENDIAN order is used always. 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 cases of ByteArray and BitArray.
      Throws:
      NullPointerException - if inputStream, array or byteOrder argument is null.
      IOException - in the same situations as in the standard DataInputStream.readFully method.
      See Also:
    • isJavaArrayWrapper

      public static boolean isJavaArrayWrapper(Array array)
      Returns true if the specified array is actually a wrapper for standard Java array, like wrappers returned by SimpleMemoryModel.asUpdatableArray(Object) method.

      More precisely, this method returns true, if and only if all the following conditions are fulfilled:

      1. array instanceof DirectAccessible; let da = (DirectAccessible) array;
      2. da.hasJavaArray();
      3. da.javaArrayOffset() == 0;
      4. array.length() == n, where n is the length of Java array da.javaArray():
        array.length() == java.lang.reflect.Array.getLength(da.javaArray()).

      In this situation, the specified AlgART array is called a wrapper of the underlying Java array da.javaArray().

      Parameters:
      array - the source AlgART array.
      Returns:
      whether it is a wrapper for standard Java array: direct-accessible array with zero offset and with length, equal to the number of elements of the underlying Java array.
      Throws:
      NullPointerException - if the argument is null.
      See Also:
    • toJavaArray

      public static Object toJavaArray(Array array)
      Returns a Java array containing all the elements in this AlgART array in proper sequence, if the length of this array is not too large (not greater than Integer.MAX_VALUE). In other case, throws TooLargeArrayException.

      The result is always a newly created Java array. Its length 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 the sense 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:

      Reverse operation — conversion of Java array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableArray(Object) method, returning a view of Java array, or by MemoryModel.valueOf(Object) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java array into AlgART array — can be performed by MemoryModel.valueOf(boolean[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java char[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableCharArray(char[]) method, returning a view of Java array, or by MemoryModel.valueOf(char[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java byte[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableByteArray(byte[]) method, returning a view of Java array, or by MemoryModel.valueOf(byte[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java short[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableShortArray(short[]) method, returning a view of Java array, or by MemoryModel.valueOf(short[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java int[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableIntArray(int[]) method, returning a view of Java array, or by MemoryModel.valueOf(int[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java long[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableLongArray(long[]) method, returning a view of Java array, or by MemoryModel.valueOf(long[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java float[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableFloatArray(float[]) method, returning a view of Java array, or by MemoryModel.valueOf(float[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java double[] array into AlgART array — can be performed by SimpleMemoryModel.asUpdatableDoubleArray(double[]) method, returning a view of Java array, or by MemoryModel.valueOf(double[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toJavaArray

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

      Reverse operation — conversion of Java array of any objects into AlgART array — can be performed by SimpleMemoryModel.asUpdatableObjectArray(Object[]) method, returning a view of Java array, or by MemoryModel.valueOf(Object[]) method of any memory model instance, which actually copies data into newly allocated array.

      Parameters:
      array - the source AlgART object array.
      Returns:
      Java array containing all of the elements in this array.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toByteJavaArray

      public static byte[] toByteJavaArray(PArray array)
      Returns a newly created Java byte[] array containing all elements in this AlgART array, cast to byte type if necessary. Equivalent to toByteJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to byte type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toByteJavaArray

      public static byte[] toByteJavaArray(byte[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to byte type if the array is not a ByteArray, and return a reference to the result. If result argument is null, creates a new byte[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new byte[array.length32()];
            }
            if (!(array instanceof ByteArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, ByteArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result byte[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to byte type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toShortJavaArray

      public static short[] toShortJavaArray(PArray array)
      Returns a newly created Java short[] array containing all elements in this AlgART array, cast to short type if necessary. Equivalent to toShortJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to short type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toShortJavaArray

      public static short[] toShortJavaArray(short[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to short type if the array is not a ShortArray, and return a reference to the result. If result argument is null, creates a new short[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new short[array.length32()];
            }
            if (!(array instanceof ShortArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, ShortArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result short[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to short type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toIntJavaArray

      public static int[] toIntJavaArray(PArray array)
      Returns a newly created Java int[] array containing all elements in this AlgART array, cast to int type if necessary. Equivalent to toIntJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to int type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toIntJavaArray

      public static int[] toIntJavaArray(int[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to int type if the array is not a IntArray, and return a reference to the result. If result argument is null, creates a new int[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new int[array.length32()];
            }
            if (!(array instanceof IntArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, IntArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result int[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to int type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toLongJavaArray

      public static long[] toLongJavaArray(PArray array)
      Returns a newly created Java long[] array containing all elements in this AlgART array, cast to long type if necessary. Equivalent to toLongJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to long type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toLongJavaArray

      public static long[] toLongJavaArray(long[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to long type if the array is not a LongArray, and return a reference to the result. If result argument is null, creates a new long[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new long[array.length32()];
            }
            if (!(array instanceof LongArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, LongArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result long[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to long type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toFloatJavaArray

      public static float[] toFloatJavaArray(PArray array)
      Returns a newly created Java float[] array containing all elements in this AlgART array, cast to float type if necessary. Equivalent to toFloatJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to float type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toFloatJavaArray

      public static float[] toFloatJavaArray(float[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to float type if the array is not a FloatArray, and return a reference to the result. If result argument is null, creates a new float[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new float[array.length32()];
            }
            if (!(array instanceof FloatArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, FloatArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result float[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to float type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toDoubleJavaArray

      public static double[] toDoubleJavaArray(PArray array)
      Returns a newly created Java double[] array containing all elements in this AlgART array, cast to double type if necessary. Equivalent to toDoubleJavaArray(null, array).

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

      Parameters:
      array - the source AlgART array.
      Returns:
      Java array containing all the elements in this array, cast to double type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toDoubleJavaArray

      public static double[] toDoubleJavaArray(double[] result, PArray array)
      Copies all elements in the source AlgART array into the result array, automatically casting the elements to double type if the array is not a DoubleArray, and return a reference to the result. If result argument is null, creates a new double[] array with a length equal to the source array length array.length(); if it is not null, its length must be ≥array.length(). If the length of the source AlgART array is too large (greater than Integer.MAX_VALUE), throws TooLargeArrayException.

      This method is equivalent to the following code:

            if (result == null) {
                result = new double[array.length32()];
            }
            if (!(array instanceof DoubleArray)) {
                array = Arrays.asFuncArray(Func.IDENTITY, DoubleArray.class, array);
            }
            array.getData(0, result);
      Parameters:
      result - the result double[] array; may be null, then it will be created automatically.
      array - the source AlgART array.
      Returns:
      a reference to result argument or (when result==null) a newly created array: Java array containing all the elements in the source AlgART array, cast to double type according to AlgART rules.
      Throws:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      IndexOutOfBoundsException - if the result argument is not null, but its length is too small: less than array.length().
      See Also:
    • toString

      public static 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:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the array length is greater than Integer.MAX_VALUE.
      See Also:
    • toString

      public static String toString(Array array, 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:
      NullPointerException - if array or separator argument is null
      IllegalArgumentException - if maxStringLength <= 0.
      See Also:
    • toString

      public static String toString(Array array, Locale locale, String format, 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:
      NullPointerException - if array or separator argument is null.
      IllegalArgumentException - if maxStringLength <= 0.
      See Also:
    • toHexString

      public static String toHexString(Array array, 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:

      • for arrays of boolean elements (BitArray), numeric representation ("0" and "1") is used instead of "false" and "true";
      • for arrays of char, byte, short, int, long elements (CharArray, ByteArray, ShortArray, IntArray, LongArray), the unsigned hexadecimal representation is used.
      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:
      NullPointerException - if array or separator argument is null.
      IllegalArgumentException - if maxStringLength <= 0.
      See Also:
    • 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:
      NullPointerException - if array argument is null.
      TooLargeArrayException - if the sum newUnsignedLength (as unsigned value) 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:
      NullPointerException - if bitArray argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      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:
      NullPointerException - if array argument is null.
      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:
      NullPointerException - if array argument is null.
      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:
      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 byte and short element types, this comparator is based on usual Java comparison: it compares signed values, where the byte -1 is interpreted as -1 (not 255, like in ByteArray.getByte(long) method).

      For float and double element types, this comparator is based on Float.compare(float, float) and Double.compare(double, double) methods. So, NaN is considered to be equal to itself and greater than all other float/double values (including POSITIVE_INFINITY), and 0.0 is considered be greater than -0.0.

      For non-primitive arrays, this 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:
      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 byte and short element types, this comparator is based on usual Java comparison: it compares signed values, where the byte -1 is interpreted as -1 (not 255, like in ByteArray.getByte(long) method).

      For float and double element types, this comparator is based on Float.compare(float, float) and Double.compare(double, double) methods. So, NaN is considered to be equal to itself and greater than all other float/double values (including POSITIVE_INFINITY), and 0.0 is considered be greater than -0.0.

      For non-primitive arrays, this 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:
      NullPointerException - if array argument is null.
    • asCharSequence

      public static CharSequence asCharSequence(CharArray charArray)
      Returns a view of the character array implementing standard CharSequence interface. The methods of the returned view do the following:
      • length() returns (int)charArray.length();
      • charAt(int index) returns charArray.getChar(index);
      • subSequence(int start, int end) returns an analogous view for (CharArray)charArray.subArray(start, end);
      • toString() Arrays.toString(charArray)
      • .

      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:
      NullPointerException - if charArray argument is null.
    • asList

      public static <E> List<E> asList(Array array, 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:
      NullPointerException - if one of the arguments is null.
      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:
    • asList

      public static <E> 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:
      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).
    • 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:
      NullPointerException - if array argument is null.
      See Also:
    • 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:
      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:
      NullPointerException - if array argument is null.
    • min

      public static int min(int a, int b, int c)
      Returns Math.min(Math.min(a, b), c) — minimum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      minimum from a, b, c.
    • max

      public static int max(int a, int b, int c)
      Returns Math.max(Math.max(a, b), c) — maximum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      maximum from a, b, c.
    • min

      public static int min(int a, int b, int c, int d)
      Returns Math.min(Math.min(a, b), Math.min(c, d)) — minimum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      minimum from a, b, c, d.
    • max

      public static int max(int a, int b, int c, int d)
      Returns Math.max(Math.max(a, b), Math.max(c, d)) — maximum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      maximum from a, b, c, d.
    • truncate

      public static int truncate(int value, int min, int max)
      Returns Math.min(Math.max(value, min), max). In other words, truncates the passed value by the range min..max.

      Note: if min>max, this method does not throw an exception, but just returns max.

      Parameters:
      value - value to correct.
      min - minimal allowed value.
      max - maximal allowed value.
      Returns:
      the passed value, truncated by the range min..max.
    • min

      public static long min(long a, long b, long c)
      Returns Math.min(Math.min(a, b), c) — minimum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      minimum from a, b, c.
    • max

      public static long max(long a, long b, long c)
      Returns Math.max(Math.max(a, b), c) — maximum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      maximum from a, b, c.
    • min

      public static long min(long a, long b, long c, long d)
      Returns Math.min(Math.min(a, b), Math.min(c, d)) — minimum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      minimum from a, b, c, d.
    • max

      public static long max(long a, long b, long c, long d)
      Returns Math.max(Math.max(a, b), Math.max(c, d)) — maximum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      maximum from a, b, c, d.
    • truncate

      public static long truncate(long value, long min, long max)
      Returns Math.min(Math.max(value, min), max). In other words, truncates the passed value by the range min..max.

      Note: if min>max, this method does not throw an exception, but just returns max.

      Parameters:
      value - value to correct.
      min - minimal allowed value.
      max - maximal allowed value.
      Returns:
      the passed value, truncated by the range min..max.
    • min

      public static float min(float a, float b, float c)
      Returns Math.min(Math.min(a, b), c) — minimum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      minimum from a, b, c.
    • max

      public static float max(float a, float b, float c)
      Returns Math.max(Math.max(a, b), c) — maximum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      maximum from a, b, c.
    • min

      public static float min(float a, float b, float c, float d)
      Returns Math.min(Math.min(a, b), Math.min(c, d)) — minimum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      minimum from a, b, c, d.
    • max

      public static float max(float a, float b, float c, float d)
      Returns Math.max(Math.max(a, b), Math.max(c, d)) — maximum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      maximum from a, b, c, d.
    • truncate

      public static float truncate(float value, float min, float max)
      Returns Math.min(Math.max(value, min), max). In other words, truncates the passed value by the range min..max.

      Note: if min>max, this method does not throw an exception, but just returns max.

      Parameters:
      value - value to correct.
      min - minimal allowed value.
      max - maximal allowed value.
      Returns:
      the passed value, truncated by the range min..max.
    • min

      public static double min(double a, double b, double c)
      Returns Math.min(Math.min(a, b), c) — minimum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      minimum from a, b, c.
    • max

      public static double max(double a, double b, double c)
      Returns Math.max(Math.max(a, b), c) — maximum from 3 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      Returns:
      maximum from a, b, c.
    • min

      public static double min(double a, double b, double c, double d)
      Returns Math.min(Math.min(a, b), Math.min(c, d)) — minimum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      minimum from a, b, c, d.
    • max

      public static double max(double a, double b, double c, double d)
      Returns Math.max(Math.max(a, b), Math.max(c, d)) — maximum from 4 values.
      Parameters:
      a - 1st value.
      b - 2nd value.
      c - 3rd value.
      d - 4thd value.
      Returns:
      maximum from a, b, c, d.
    • truncate

      public static double truncate(double value, double min, double max)
      Returns Math.min(Math.max(value, min), max). In other words, truncates the passed value by the range min..max.

      Note: if min>max, this method does not throw an exception, but just returns max.

      Parameters:
      value - value to correct.
      min - minimal allowed value.
      max - maximal allowed value.
      Returns:
      the passed value, truncated by the range min..max.
    • round32

      public static int round32(double value)
      Analog of StrictMath.round, but producing nearest int result in range -Integer.MAX_VALUE..+Integer.MAX_VALUE (with saturation in a case of overflow).

      Note: Integer.MIN_VALUE is also impossible in the result: it will be replaced with -Integer.MAX_VALUE (=Integer.MIN_VALUE+1).

      Parameters:
      value - a floating-point value to be rounded to a int.
      Returns:
      the value of the argument rounded to the nearest int value in range -Integer.MAX_VALUE..+Integer.MAX_VALUE.
    • 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:
      NullPointerException - if multipliers argument is null.
      IndexOutOfBoundsException - if from<0 or to>multipliers.length.
      IllegalArgumentException - if from>to.
      See Also:
    • 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:
      NullPointerException - if multipliers argument is null.
      See Also:
    • 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:
    • 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:
      NullPointerException - if positions argument is null.
      IllegalArgumentException - if length<=0, or if some of passed positions are not in 0..length-1 range.
    • splitToRanges

      public static void splitToRanges(int[] result, int n)
    • splitToRanges

      public static void splitToRanges(long[] result, long n)
    • 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 InterruptedException
      Performs a loop of 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:
      IllegalArgumentException - if timeoutInMilliseconds <= 0.
      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 Exception> void throwException(Class<? extends T> exceptionClass, Throwable exception) throws T
      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 Exception
    • throwUncheckedException

      public static void throwUncheckedException(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(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:
      NullPointerException - if task or whenToExecute is null.