In addition to Python’s built-in data types, Jython has the benefit of using Java collection classes by importing the java.util package. The following code describes the classes given below −
import java.util.ArrayList as ArrayList arr = ArrayList() arr.add(10) arr.add(20) print "ArrayList:",arr arr.remove(10) #remove 10 from arraylist arr.add(0,5) #add 5 at 0th index print "ArrayList:",arr print "element at index 1:",arr.get(1) #retrieve item at index 1 arr.set(0,100) #set item at 0th index to 100 print "ArrayList:",arr
The above Jython script produces the following output −
C:\jython27\bin>jython arrlist.py ArrayList: [10, 20] ArrayList: [5, 20] element at index 1: 20 ArrayList: [100, 20]
Jython also implements the Jarray Object, which allows construction of a Java array in Python. In order to work with a jarray, simply define a sequence type in Jython and pass it to the jarrayobject along with the type of object contained within the sequence. All values within a jarray must be of the same type.
The following table shows the character typecodes used with a jarray.
Character Typecode | Corresponding Java Type |
---|---|
Z | Boolean |
C | char |
B | byte |
H | short |
I | int |
L | long |
F | float |
D | double |
The following example shows construction of jarray.
my_seq = (1,2,3,4,5) from jarray import array arr1 = array(my_seq,'i') print arr1 myStr = "Hello Jython" arr2 = array(myStr,'c') print arr2
Here my_seq is defined as a tuple of integers. It is converted to Jarray arr1. The second example shows that Jarray arr2 is constructed from mySttr string sequence. The output of the above script jarray.py is as follows −
array('i', [1, 2, 3, 4, 5]) array('c', 'Hello Jython')