I l@ve RuBoard |
Java Arrays and jarrayThe closest thing to a Java array in Python is a tuple. Remember that a tuple is immutable and a list is mutable. Like a list, a Java array is mutable but, like a tuple, it's of fixed length. You may think that a tuple or a list is a likely candidate for an array, but that's not exactly the case. You see, an array is like a homogeneous tuple or list�every item in it is of the same type; but a tuple is heterogeneous�items in it can be of different types. A lot of Java methods have Java arrays as arguments, so when you pass an array to a Java method, Python has to guarantee that it will be homogeneously typed. Just a note: Because they're strongly typed, Java arrays can hold Java objects or primitive types. Jython adds PyArray class support for Java arrays�org.python.core.PyArray to be exact. Instances of PyArray are returned from Java methods that return Java arrays. You need to create instances of PyArray to pass to Java methods that require arrays. Python makes creating a PyArray painless with the jarray module, which defines two public functions, described in Table 11-4.
The type argument for both zeros() and array() can be either a string or a Java class object. You can use a single-character string typecode to specify that the array will hold primitive values. Table 11-5 shows the typecodes and their primitive types. Here's an example of creating arrays with the array() and zeros() methods from the jarray module. Create a Boolean array using the array() method.
Inspect its contents.
See what type it is.
Change its values.
You can use the same operations on an array that you use on a sequence (a tuple or a list). Here's an example:
Even though an array is mutable, it's still of fixed length; that means that you can't append to it as you can a Python list. If you try, you'll get an attribute error.
Let's create an array with the zeros() method.
As the above example shows, you can think of PyArray essentially as a Python built-in type that's specific to Jython. Like other features Jython has for integrating with Java, PyArrays are transparent to the programmer (when returned from a Java method). Creating one is easy with Jython's jarray module. |
I l@ve RuBoard |
No comments:
Post a Comment