Main Content

Create Array of Java Objects

The MATLAB® javaArray function lets you create a Java® array that MATLAB handles as a single multidimensional array. You specify the number and size of the array dimensions along with the class of objects you intend to store in it. Using the one-dimensional Java array as its primary building block, MATLAB then builds a Java array that satisfies the dimensions requested in the javaArray command.

To create a Java object array, use the MATLAB javaArray function. For example, the following command creates a Java array of four lower-level arrays, each containing five objects of the java.lang.Double class.

dblArray = javaArray('java.lang.Double',4,5);

The javaArray function does not initialize values in the array. This code copies the first four rows of MATLAB array A, containing randomly generated data, into dblArray.

A = rand(5);
for m = 1:4
    for n = 1:5
        dblArray(m,n) = java.lang.Double(A(m,n));
    end
end

dblArray
dblArray =

  java.lang.Double[][]:

    [0.7577]    [0.7060]    [0.8235]    [0.4387]    [0.4898]
    [0.7431]    [0.0318]    [0.6948]    [0.3816]    [0.4456]
    [0.3922]    [0.2769]    [0.3171]    [0.7655]    [0.6463]
    [0.6555]    [0.0462]    [0.9502]    [0.7952]    [0.7094]

You must convert each element of A to the java.lang.Double type. For more information, see Pass Java Objects.

Create Array of Primitive Java Types

To pass an array of a primitive Java type to a Java method, you must pass in an array of the equivalent MATLAB type. For the type mapping details, see MATLAB Type to Java Type Mapping.

For example, create a java.awt.Polygon by looking at the constructors in the following methods window.

methodsview('java.awt.Polygon')

This constructor uses an array of Java int.

	Polygon	(int[],int[],int)

MATLAB converts a MATLAB double to a Java scalar or array int. Create two MATLAB arrays, identifying four points of a polygon.

x = [10 40 95 125 10];
y = [50 15 0 60 50];
polygon = java.awt.Polygon(x,y,length(x));

To call the Polygon object method contains, look at its signature in the method window.

boolean	contains	(double,double)

MATLAB converts a MATLAB double to a Java double. This statement checks if the point (50,40) is within the polygon.

contains(polygon,50,40)
ans =

  logical

   1

See Also

Related Topics