Category: Proxy usage

Q

What else should I know about array types?

A

Array types are the types with the biggest differences to expected behavior. This is mostly due to the fact that C++ array types and Java array types are totally different animals. A Java array is an object whereas a C++ array is a pointer to a contiguous memory range. A Java multi-dimensional array is an object containing other array objects whereas a C++ array is... a pointer to a contiguous memory range.

Java arrays have some interesting type compatibility characteristics, expressible as is a relationships:

  • String[] is an Object[]
  • String[][] is an Object[][]
  • String[][] is an Object[]

We simply could not come up with a good way to express these type relationships in the array proxy types. Consequently, while in Java you can pass a String[][] to a method that is declared to expect an Object[], in C++ you can not. You can't even pass a proxy array instance where an Object is expected because the proxy array types do not extend the Object proxy type. Whenever you have to use a proxy array instance in a place that expects a proxy instance of another (compatible) type, you have to dyna_cast() the instance to the expected type.

C++ arrays are virtually useless with polymorphic type hierarchies. An array declared as an Object[] can never safely hold anything but Object instances because the array elements are expected at memory locations that depend on the size of the element type. If you were to put a String instance (with a bigger instance size) in the array, some of the String's data would overlap the data area allocated for the next Object.

The whole point of arrays is of course to hold an ordered sequence of elements, often many elements. While you can access proxy array elements one by one through convenient subscript operators, that's not always the most efficient way to do so. Even in pure C++, you sometimes optimize array initialization by block-copying data directly into the array's memory range. Imagine how much more effective this optimization is if every array element access has a measurable cost (due of the JNI overhead). Therefore, if you perform an activity with every member of a large array, you might be better off copying all members into a native array using a block accessor and then operating on the elements there. Check out the array reference for more details.


Copyright 2006-2011 by Codemesh, Inc., ALL RIGHTS RESERVED

:
frequently asked questions
home products support customers partners newsroom about us contact us