- Jython - Dialogs
- Jython - Menus
- Jython - Event Handling
- Jython - Layout Management
- Jython - Using the Swing GUI library
- Jython - JDBC
- Jython - Servlets
- Jython - NetBeans Plugin & Project
- Jython - A Project in Eclipse
- Jython - Eclipse Plugin
- Jython - Java Application
- Jython - Package
- Jython - Modules
- Jython - Functions
- Jython - Loops
- Jython - Decision Control
- Jython - Using Java Collection Types
- Jython - Variables and Data Types
- Jython - Importing Java Libraries
- Jython - Installation
- Jython - Overview
- Jython - Home
Jython Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Jython - Using Java Collection Types
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 −
Java ArrayList object with add()
remove()
get() and set() methods of the ArrayList class.
import java.util.ArrayList as ArrayList arr = ArrayList() arr.add(10) arr.add(20) print "ArrayList:",arr arr.remove(10) #remove 10 from arraypst 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:jython27in>jython arrpst.py ArrayList: [10, 20] ArrayList: [5, 20] element at index 1: 20 ArrayList: [100, 20]
Jarray Class
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 )Advertisements