Jythonspecific Collections¶

Chapter 2: Data Types and Referencing — Jython Book v1.0 documentation

Jython-specific Collections

There are a number of Jython-specific collection objects that are available for use.
Most of these collection objects are used to pass data into Java classes and so
forth, but they add additional functionality into the Jython implementation that will
assist Python newcomers that are coming from the Java world. Nonetheless, many of
these additional collection objects can be quite useful under certain situations.

In the Jython 2.2 release, Java collection integration was introduced. This enables a
bidirectional interaction between Jython and Java collection types. For instance, a
Java ArrayList can be imported in Jython and then used as if it were part of the
language. Prior to 2.2, Java collection objects could act as a Jython object, but
Jython objects could not act as Java objects. For instance, it is possible to use a
Java ArrayList in Jython and use methods such as add(), remove(), and get(). You will
see in the example below that using the add() method of an ArrayList will add an
element to the list and return a boolean to signify the success or failure of the
addition. The remove() method acts similarly, except that it removes an element
rather than adding it.

Listing 2-27. Example of Using Java Oriented Collection in Jython

# Import and use a Java ArrayList

>>> import java.util.ArrayList as ArrayList

>>> arr = ArrayList()

#  Add method will add an element to the list and return a boolean to signify
successsful addition

>>> arr.add(1)

True

>>> arr.add(2)

True

>>> print arr

[1, 2]

Ahead of the integration of Java collections, Jython also had implemented the jarray
object which basically allows for the construction of a Java array in Jython. In
order to work with a jarray, simply define a sequence type in Jython and pass it to
the jarray object along with the type of object contained within the sequence. The
jarray is definitely useful for creating Java arrays and then passing them into java
objects, but it is not very useful for working in Jython objects. Moreover, all
values within a jarray must be the same type. If you try to pass a sequence
containing multiple types to a jarray then you’ll be given a TypeError of one kind or
another. See Table 2-8 for a listing of character typecodes used with jarray.

原文地址:https://www.cnblogs.com/lexus/p/2370699.html