Class PyArray
- All Implemented Interfaces:
Serializable,Cloneable,BufferProtocol,Traverseproc
- Direct Known Subclasses:
PyArrayDerived
array.array. This is a wrapper around native Java arrays. Instances of
PyArray are created either by Java functions or directly by the jarray module
(q.v.).
The range of possible element (item) types exceeds that in Python, since it allows for arbitrary Java classes. This extended behaviour is accessible from Python by supplying a Java type (class) to the constructor, where one might have used a single character type code. For example:
>>> ax = array.array(BigDecimal, (BigDecimal(str(n)) for n in range(5))) >>> ax array(java.math.BigDecimal, [0, 1, 2, 3, 4]) >>> type(ax[2]) <type 'java.math.BigDecimal'>
| typecode | Python type | Java type | serialised size | signed |
|---|---|---|---|---|
b |
int |
byte |
1 | |
B |
int |
byte |
1 | unsigned |
h |
int |
short |
2 | |
H |
int |
short |
2 | unsigned |
i |
int |
int |
4 | |
I |
long |
int |
4 | unsigned |
l |
long |
long |
8 | |
L |
long |
long |
8 | unsigned |
f |
float |
float |
4 | |
d |
float |
double |
8 | |
c |
str |
byte |
1 | unsigned |
u |
unicode |
int |
1 | unsigned |
z |
bool |
boolean |
1 |
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class org.python.core.PyObject
PyObject.ConversionException -
Field Summary
FieldsFields inherited from class org.python.core.PyObject
gcMonitorGlobal -
Constructor Summary
ConstructorsConstructorDescriptionCreate aPyArraywith the given array item class and number of zero ornullelements.Create aPyArraywith the given array item class and content.Create aPyArraywith the given array item class and content initialised from a Python object (iterable).Create aPyArrayas a copy of another.Create a defaultPyArrayof specific Python type (for sub-class use). -
Method Summary
Modifier and TypeMethodDescriptionEquivalent to the standard Python __add__ method.Equivalent to the standard Python __iadd__ method.Equivalent to the standard Python __imul__ method.int__len__()Length of the array (as the number of elements, not a storage size).Equivalent to the standard Python __mul__ method.Used for pickling.Equivalent to the standard Python __rmul__ method.__tojava__(Class<?> c) Equivalent to the Jython __tojava__ method.voidAppend new value x to the end of the array.static PyArrayCreate aPyArraywith the given array item type and content initialised from a Python object (iterable).static PyArrayCreate aPyArraystoringctypetypes and being initialised withinit.final voidarray_append(PyObject value) voidstatic Class<?> array_class(Class<?> type) final intarray_count(PyObject value) final voidarray_extend(PyObject iterable) final voidarray_fromfile(PyObject f, int count) final voidarray_fromlist(PyObject obj) final intarray_index(PyObject value) final voidarray_insert(int index, PyObject value) final PyObjectarray_pop(int i) Removes the item at the indexifrom the array and returns it.final voidarray_remove(PyObject value) final voidfinal voidfinal PyObjectfinal PyObjectfinal PyUnicodevoidvoidbyteswap()"Byteswap" all items of the array.static Class<?> char2class(char typecode) Converts a character code for the array type to the JavaClassof the elements of the implementation array.clone()Implementation ofCloneableinterface.Return the number of occurrences of x in the array.voidAppend items fromiterableto the end of the array.intFill the current array with primitive values (of the type the array holds) from a stream, starting at array index zero, up to the capacity of the array, without resizing.voidReadcountitems (as machine values) from the file objectfand append them to the end of the array.voidAppend items from the list.intfromstring(int start, String input) Read primitive values from a stream into a slice of the array, defined by a start and the number of items encoded in the bytes.voidfromstring(String input) Append items from the string, interpreting the string as an array of bytes (as if it had been read from a file using thefromfile()method).voidfromstring(PyObject input) Append items from the object, which is a byte string of some kind (PyStringor object with the buffer interface providing bytes).voidfromunicode(PyUnicode input) getArray()Return the internal Java array storage of thePyArrayinstancegetBuffer(int flags) Method by which the consumer requests the buffer from the exporter.intGetter for the item size of the array element type.intDeprecated.Return either a Python-stylearray.arraytype code for the element (item) type or the Java class name.inthashCode()Return the smallest i such that i is the index of the first occurrence ofvaluein the array.voidInsert a new item with valuevaluein the array before positionindex.pop()Removes the last item from the array and return it.pop(int index) Removes the item with the indexindexfrom the array and returns it.booleanOptional operation.voidRemove the first occurrence ofvaluefrom the array.voidreverse()Reverse the elements in the arrayvoidset(int i, byte value) Set element in an array of element type 'b','B', or 'c' to a Javabyte.voidset(int i, char value) Set element to integer value given as a Javachar, tolerating primitive integer values in arrays of Unicode character,intorlong.voidset(int i, int value) Set element to integer value, tolerating primitive integer values in arrays of Unicode character,intorlong.voidSet an element in the array - the index needs to exist, this method does not automatically extend the array.voidWrite all items (as machine values) to the file objectf.tolist()Convert the array to an ordinary list with the same items.inttoStream(OutputStream os) Generic stream writer to write the entire contents of the array to the stream as primitive types.tostring()Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by thetofile()method.)toString()intTraverses all directly containedPyObjects.static PyArrayzeros(int n, char typecode) Create aPyArraywith the given array type code and number of zero elements.static PyArrayCreate aPyArraywith the given array item class and number of zero ornullelements.Methods inherited from class org.python.core.PySequence
__delitem__, __delslice__, __eq__, __finditem__, __finditem__, __ge__, __getitem__, __getslice__, __gt__, __iter__, __le__, __lt__, __ne__, __nonzero__, __setitem__, __setitem__, __setslice__, isMappingType, isNumberType, isSequenceTypeMethods inherited from class org.python.core.PyObject
__abs__, __and__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __call__, __cmp__, __coerce__, __coerce_ex__, __complex__, __contains__, __delattr__, __delattr__, __delete__, __delitem__, __delslice__, __dir__, __div__, __divmod__, __ensure_finalizer__, __findattr__, __findattr__, __findattr_ex__, __finditem__, __float__, __floordiv__, __format__, __get__, __getattr__, __getattr__, __getitem__, __getnewargs__, __getslice__, __hash__, __hex__, __iand__, __idiv__, __idivmod__, __ifloordiv__, __ilshift__, __imod__, __index__, __int__, __invert__, __ior__, __ipow__, __irshift__, __isub__, __iternext__, __itruediv__, __ixor__, __long__, __lshift__, __mod__, __neg__, __not__, __oct__, __or__, __pos__, __pow__, __pow__, __radd__, __rand__, __rdiv__, __rdivmod__, __reduce_ex__, __reduce_ex__, __repr__, __rfloordiv__, __rlshift__, __rmod__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __set__, __setattr__, __setattr__, __setitem__, __setslice__, __str__, __sub__, __truediv__, __trunc__, __unicode__, __xor__, _add, _and, _callextra, _cmp, _div, _divmod, _doget, _doget, _doset, _eq, _floordiv, _ge, _gt, _iadd, _iand, _idiv, _idivmod, _ifloordiv, _ilshift, _imod, _imul, _in, _ior, _ipow, _irshift, _is, _isnot, _isub, _itruediv, _ixor, _jcall, _jcallexc, _jthrow, _le, _lshift, _lt, _mod, _mul, _ne, _notin, _or, _pow, _rshift, _sub, _truediv, _xor, asDouble, asIndex, asIndex, asInt, asInt, asIterable, asLong, asLong, asName, asName, asString, asString, asStringOrNull, asStringOrNull, bit_length, conjugate, delDict, delType, dispatch__init__, equals, fastGetClass, fastGetDict, getDict, getType, implementsDescrDelete, implementsDescrGet, implementsDescrSet, invoke, invoke, invoke, invoke, invoke, invoke, isCallable, isDataDescr, isIndex, isInteger, noAttributeError, object___subclasshook__, readonlyAttributeError, setDict, setType
-
Field Details
-
TYPE
-
-
Constructor Details
-
PyArray
Create a defaultPyArrayof specific Python type (for sub-class use).- Parameters:
subtype- actual Python type
-
PyArray
Create aPyArraywith the given array item class and content. IfitemClassis one of the primitive types used to implement the "single letter" type codes, the type code of the array will be a signed zero of that item class.- Parameters:
itemClass- of elements in the arraydata- content array
-
PyArray
Create aPyArraywith the given array item class and content initialised from a Python object (iterable).- Parameters:
itemClass- of elements in the arrayinitial- provider of initial contents
-
PyArray
Create aPyArraywith the given array item class and number of zero ornullelements. IfitemClassis one of the primitive types used to implement the "single letter" type codes, the type code of the array will be a signed zero of that item class.- Parameters:
itemClass- of elements in the arrayn- number of (zero ornull) elements
-
PyArray
Create aPyArrayas a copy of another.- Parameters:
toCopy- the other array
-
-
Method Details
-
zeros
Create aPyArraywith the given array type code and number of zero elements.- Parameters:
n- number of (zero ornull) elementstypecode- of elements in the array- Returns:
- created array
-
zeros
Create aPyArraywith the given array item class and number of zero ornullelements. IfitemClassis one of the primitive types used to implement the "single letter" type codes, the type code of the array will be a signed zero of that item class.- Parameters:
n- number of (zero ornull) elementsitemClass-- Returns:
- created array
-
array
Create aPyArraywith the given array item type and content initialised from a Python object (iterable).- Parameters:
seq- to suply contenttypecode-- Returns:
- created array
-
array_class
-
array
Create aPyArraystoringctypetypes and being initialised withinit.- Parameters:
init- an initialiser for the array - can bePyStringorPySequence(includingPyArray) or iterable type.itemClass-Classof the elements stored in the array.- Returns:
- a new PyArray
-
hashCode
public int hashCode() -
array___iter__
-
__imul__
Description copied from class:PyObjectEquivalent to the standard Python __imul__ method. -
__mul__
Description copied from class:PyObjectEquivalent to the standard Python __mul__ method. -
__rmul__
Description copied from class:PyObjectEquivalent to the standard Python __rmul__ method. -
__iadd__
Description copied from class:PyObjectEquivalent to the standard Python __iadd__ method. -
__add__
Description copied from class:PyObjectEquivalent to the standard Python __add__ method. -
__len__
public int __len__()Length of the array (as the number of elements, not a storage size). -
__reduce__
Description copied from class:PyObjectUsed for pickling. Default implementation calls object___reduce__.- Overrides:
__reduce__in classPyObject- Returns:
- a tuple of (class, tuple)
-
toString
-
__tojava__
Description copied from class:PyObjectEquivalent to the Jython __tojava__ method. Tries to coerce this object to an instance of the requested Java class. Returns the special objectPy.NoConversionif thisPyObjectcan not be converted to the desired Java class.- Overrides:
__tojava__in classPySequence- Parameters:
c- targetClassfor the conversion- Returns:
- Java object converted to required class type if possible.
-
array_append
-
append
Append new value x to the end of the array.- Parameters:
value- item to be appended to the array
-
array_byteswap
public void array_byteswap() -
byteswap
public void byteswap()"Byteswap" all items of the array. This is only supported for values which are 1, 2, 4, or 8 bytes in size; for other types of values,RuntimeErroris raised. It is useful when reading data from a file written on a machine with a different byte order. -
clone
Implementation ofCloneableinterface.- Returns:
- copy of current PyArray
-
char2class
Converts a character code for the array type to the JavaClassof the elements of the implementation array.- Parameters:
typecode- character code for the array type- Returns:
Classof the native itemClass- Throws:
PyIgnoreMethodTag
-
array_count
-
count
Return the number of occurrences of x in the array.- Parameters:
value- instances of the value to be counted- Returns:
- number of time value was found in the array.
-
array_extend
-
extend
Append items fromiterableto the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised. If iterable is not an array, it must be iterable and its elements must be the right type to be appended to the array.- Parameters:
iterable- iterable object used to extend the array
-
array_fromfile
-
fromfile
Readcountitems (as machine values) from the file objectfand append them to the end of the array. If less thancountitems are available, EOFError is raised, but the items that were available are still inserted into the array.fmust be a real built-in file object; something else with a read() method won't do.- Parameters:
f- Python builtin file object to retrieve datacount- number of array elements to read
-
array_fromlist
-
fromlist
Append items from the list. This is equivalent tofor x in list: a.append(x)except that if there is a type error, the array is unchanged.- Parameters:
obj- input list object that will be appended to the array
-
fillFromStream
Fill the current array with primitive values (of the type the array holds) from a stream, starting at array index zero, up to the capacity of the array, without resizing. Data are read until the array is filled or the stream runs out. If the stream does not contain a whole number of items (possible if the item size is not one byte), the behaviour in respect of the final partial item and stream position is not defined.- Parameters:
is- InputStream to source the data from- Returns:
- number of primitives successfully read
- Throws:
IOException- reflecting I/O errors during reading
-
fromstring
Append items from the object, which is a byte string of some kind (PyStringor object with the buffer interface providing bytes). The string of bytes is interpreted as an array of machine values (as if it had been read from a file using thefromfile()method).- Parameters:
input- string of bytes containing array data
-
fromstring
Append items from the string, interpreting the string as an array of bytes (as if it had been read from a file using thefromfile()method). The bytes encode primitive values of the type appropriate to the array,- Parameters:
input- string of bytes containing array data
-
fromstring
Read primitive values from a stream into a slice of the array, defined by a start and the number of items encoded in the bytes. Data are read until the array slice is filled or the stream runs out. Data in the array beyond the slice are not altered. Write a slice of the array with primitive values items from the string, interpreting the string as an array of bytes (as if it had been read from a file using thefromfile()method). The bytes encode primitive values of the type appropriate to the array,- Parameters:
start- first element index to read intoinput- string of bytes containing array data- Returns:
- number of primitives successfully read (
=count, if not ended by EOF)
-
fromunicode
-
getArray
Return the internal Java array storage of thePyArrayinstance- Returns:
- the
Arraystore. - Throws:
PyIgnoreMethodTag
-
getItemsize
public int getItemsize()Getter for the item size of the array element type.The sizes returned by this method represent the number of bytes used to store the type. In the case of streams of primitive values, this is the number of bytes written to, or read from a stream. The amount of memory occupied by each item is an internal matter for Java.
This method is used by other methods to define read/write quanta from strings and streams.
- Returns:
- number of bytes used to store array type, relevant when serialising to an array of bytes, or the reverse.
-
getStorageSize
Deprecated.UsegetItemsize()instead which (since 2.7.3) gives the same result.Getter for the storage size of the array's type, relevant when serialising to an array of bytes, or the reverse.- Returns:
- actual storage size
-
getTypecode
Return either a Python-stylearray.arraytype code for the element (item) type or the Java class name.- Returns:
- single character type code or simple class name
-
array_index
-
index
Return the smallest i such that i is the index of the first occurrence ofvaluein the array.- Parameters:
value- value to find the index of- Returns:
- index of the first occurrence of
value
-
array_insert
-
insert
Insert a new item with valuevaluein the array before positionindex. Negative values are treated as being relative to the end of the array.- Parameters:
index- insert positionvalue- value to be inserted into array
-
array_pop
Removes the item at the indexifrom the array and returns it. The optional argument defaults to -1, so that by default the last item is removed and returned. -
pop
Removes the last item from the array and return it. -
pop
Removes the item with the indexindexfrom the array and returns it.- Parameters:
index- array location to be popped from the array- Returns:
- array element popped from index
-
array_remove
-
remove
Remove the first occurrence ofvaluefrom the array.- Parameters:
value- array value to be removed
-
array_reverse
public final void array_reverse() -
reverse
public void reverse()Reverse the elements in the array -
set
Set an element in the array - the index needs to exist, this method does not automatically extend the array. SeeAbstractArray.setSize()orAbstractArray.ensureCapacity()for ways to extend capacity.This code specifically checks for overflows of the integral types: byte, short, int and long.
- Parameters:
i- index of the element to be setvalue- value to set the element to
-
set
public void set(int i, int value) Set element to integer value, tolerating primitive integer values in arrays of Unicode character,intorlong. Negative values assigned to unsigned elements adopt their wrapped unsigned values.- Parameters:
i- index to setvalue- to set
-
set
public void set(int i, char value) Set element to integer value given as a Javachar, tolerating primitive integer values in arrays of Unicode character,intorlong.- Parameters:
i- index to setvalue- to set
-
set
public void set(int i, byte value) Set element in an array of element type 'b','B', or 'c' to a Javabyte.- Parameters:
i- index to setvalue- to set
-
array_tofile
-
array_write
-
tofile
Write all items (as machine values) to the file objectf.- Parameters:
f- Python builtin file object to write data
-
array_tolist
-
tolist
Convert the array to an ordinary list with the same items.- Returns:
- array contents as a list
-
toStream
Generic stream writer to write the entire contents of the array to the stream as primitive types.- Parameters:
os- OutputStream to sink the array data to- Returns:
- number of bytes successfully written
- Throws:
IOException
-
array_tostring
-
tostring
Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by thetofile()method.) -
array_tounicode
-
tounicode
-
getBuffer
Method by which the consumer requests the buffer from the exporter. The consumer provides information on its ability to understand buffer navigation. Each consumer requesting a buffer in this way, when it has finished using it, should make a corresponding call toPyBuffer.release()on the buffer it obtained, orPyBuffer.close()using try-with-resources, since some objects alter their behaviour while buffers are exported.The
PyBufferreturned from this method is a one-dimensional array of single byte items that allows modification of the object state. The existence of this export prohibits resizing the array. This prohibition is not only on the consumer of the view but extends to operations on the underlying array, such asinsert(int, PyObject)orpop().- Specified by:
getBufferin interfaceBufferProtocol- Parameters:
flags- specifying features demanded and the navigational capabilities of the consumer- Returns:
- exported buffer
-
traverse
Description copied from interface:TraverseprocTraverses all directly containedPyObjects. Like in CPython,argmust be passed unmodified tovisitas its second parameter. IfVisitproc.visit(PyObject, Object)returns nonzero, this return value must be returned immediately by traverse.Visitproc.visit(PyObject, Object)must not be called with anullPyObject-argument.- Specified by:
traversein interfaceTraverseproc
-
refersDirectlyTo
Description copied from interface:TraverseprocOptional operation. Should only be implemented if it is more efficient than callingTraverseproc.traverse(Visitproc, Object)with a visitproc that just watches out forob. Must returnfalseifobisnull.- Specified by:
refersDirectlyToin interfaceTraverseproc- Throws:
UnsupportedOperationException
-
getItemsize()instead which (since 2.7.3) gives the same result.