Multidimensional arrays and arrays of arrays

Multidimensional arrays and arrays of arrays

Post by Philip » Fri, 16 Jan 2009 20:49:49


Hello
How can I distinguish if an array is multidimensional of if it just
contains an array? Or put it another way how can I tell at runtime
whether a/b in the example below is an array containing an array, or
if it is a multidimensional array.
If I know beforehand exactly which type it is, I can use instanceof
(see example), but I don't (especially the number of dimensions, I
don't know).
Else I can call getClass().getName() on the object and see if it
starts with "[[" (pretty ugly IMHO).
Is there another, cleaner method to do this?

public static void main(String[] args) {
Object[] a = new Object[1];
a[0] = new float[12];

Object b = new float[1][12];

if(a instanceof float[][]){
System.out.println("a is float[][]");
}
if(b instanceof float[][]){
System.out.println("b is float[][]");
}
}

prints "b is float[][]" (but not for a) as expected.

Phil
 
 
 

Multidimensional arrays and arrays of arrays

Post by Joshua Cra » Fri, 16 Jan 2009 20:58:34


Why do you want to distinguish? All arrays are subclasses of Object,
which means an Object[] will capture all multidimensional arrays
(although also regular Object arrays as well)....

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth

 
 
 

Multidimensional arrays and arrays of arrays

Post by RedGrittyB » Fri, 16 Jan 2009 21:15:47


You cant new a primitive type. I'll assume Float everywhere you wrote float.


This is a compile time error (in Eclipse at least) - a [] isn't a [][]!

Did you intend to write "a instanceof Float[]" ?





Since "a" can contain any type of object, wouldn't it be wrong for
instanceof to report "a" as being of type Float[][]?

Consider
Object[] a = new Object[2];
a[0] = new Float[12];
a[1] = Color.RED;

is a instanceof Float[]?
is a instanceof Color[]?

surely it is just instanceof Object[][]

In these circumstances is it meaningfull to apply instanceof to anything
other than a single element of a?

a[0] instanceof Float is true
a[1] instanceof Color is true
a instanceof Object[] is true

--
RGB
 
 
 

Multidimensional arrays and arrays of arrays

Post by Philip » Fri, 16 Jan 2009 21:39:19

On Jan 15, 1:15m, RedGrittyBrick < XXXX@XXXXX.COM >


> > Object[] a = new Object[1]; >>>> a[0] = new float[12];> >> > You cant new a primitive type. I'll assume Float everywhere you wrote float.

Nope. I new an array of primitive type, not a primitive type . (and
that example works on my machine)
> > > Object b = new float[1][12]>
> This is a compile time error (in Eclipse at least) - a [] isn't a [][>! >>
> Did you intend to write "a instanceof Float[]" ?

No, and that compiles OK here.> > > > System.out.println("a is float[][>">;
> > > }
> > if(b instanceof float>]>]){
> > System.out.println("b is floa>[>[]");> > > gt;} >>>> }
>
> > prints "b is float[][]" but not for a) as>ex>ected.
>
> Since "a" can contain any type of object, wouldn't it be>wrong for
> instanceof to report "a" as being of type Float[][]?

Yes evidently. I just wanted to make clear that you can't determine if
an array is a multidimensional array, by checking if the first element
of the array is an array itself.

I have come up with some code which works pretty good for arrays of
size different than 0 in all dimensions. Unfuortunately it fails when
any dimension has length 0.

public static int getNumberOfDimension(Object[] src){
int dim = 1;
if (src instanceof Object[][]) {
// using recursion to reach all dimensions
if>src.length > 0)
dim += getNumberOfDimension((Object[])src[0]);
}
// handling primitive types explicitly
else if(src instanceof boolean[][] ||
src instanceof byte[][] ||
src instanceof short[][] ||
src instanceof int[][] ||
src instanceof long[][] ||
src instanceof float[][] ||
src instanceof double[][]){
dim = 2;
}
return dim;
}

Phil
 
 
 

Multidimensional arrays and arrays of arrays

Post by Sigfrie » Fri, 16 Jan 2009 21:57:52

Philipp a rit :



To access the second dimension data, the first dimension must have at
least 1 element, so you can use your hack wich needs > 0 length arrays.
 
 
 

Multidimensional arrays and arrays of arrays

Post by ram » Fri, 16 Jan 2009 22:17:46

Philipp < XXXX@XXXXX.COM > writes:

It is just an array containing an array.
 
 
 

Multidimensional arrays and arrays of arrays

Post by Joshua Cra » Sat, 17 Jan 2009 01:23:14


There is a method in java.util.Arrays (deepToString) which will return a
string of the form "[foo, bar, [4, ..., a]]" that iterates over
multidimensional arrays, with the added benefit that it can detect an
array which contains itself.

Would this be sufficient?

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
 
 
 

Multidimensional arrays and arrays of arrays

Post by Patricia S » Sat, 17 Jan 2009 01:29:54


Use the Class object's query methods, rather than extracting the name
and parsing it:

/**
* Test for array-of-arrays
* @param x Non-null reference to an object.
* @return true if, and only if, x is a reference to an
* array of arrays.
*/
public static boolean isArrayOfArrays(Object x){
Class<? extends Object> xClass = x.getClass();
if(! xClass.isArray()){
return false;
}else{
return xClass.getComponentType().isArray();
}
}
 
 
 

Multidimensional arrays and arrays of arrays

Post by Mark Spac » Sat, 17 Jan 2009 02:19:09

atricia Shanahan wrote:


Isn't "extends Object" redundant? The upper bound of all wildcards is
always Object.

I just happened to be writing some code similar to what the OP is asking
about. I was playing around with "Java lamda functions" and wanted to
see if I could make a method take any type of array, Collection, or Map.
The following code is presented without further comment, just as an
example to inspire thought.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package evaluator;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Eval1
{
/**
* @param args the command line arguments
*/
public static void main( String[] args ) throws LamdaException
{
Evaluater<Double> evalPlus3 = new Evaluater<Double>()
{
@Override
public Double eval( Double o )
{
return o + 3.0;
}
};
Evaluater<Object> evalPrintln = new Evaluater<Object>()
{
@Override
public Void eval( Object o ) {
System.out.println( o );
return null;
}
};
EvaluaterTransform<Double,String> evalFmt = new
EvaluaterTransform<Double,String>() {
@Override
public String eval( Double d ) {
return String.format( "%06.2g", d );
}
};

EvaluaterAggregation<Double,String> fmtString =
new EvaluaterAggregation<Double,String>() {

StringBuilder sb = new StringBuilder();

public void eval( Double o )
{
sb.append( String.format( "%06.2g", o));
}

public String getResult()
{
return sb.toString();
}

};

double[] dArray = {1.2, 2.3, 3.4};
ArrayList<Double> dAL = new ArrayList<Double>();
dAL.add( 4.5 );
dAL.add( 5.6 );
HashMap<String, Double> sdHM = new HashMap<String, Double>();
sdHM.put( "one", 6.7 );
sdHM.put( "two", 7.8 );
System.out.println( Arrays.toString( (double[]) lamda( dArray,
evalPlus3 ) ) );
System.out.println( lamda( dAL, evalPlus3 ) );
System.out.println( lamda( sdHM, evalPlus3 ) );
lamda( lamda(dArray, evalPlus3), evalPrintln );
lamda( lamda(dArray, evalFmt), evalPrintln );
// TODO car, cdr
// lamdaFirst, lamdaSkipFirst ?
// new class LamdaList which supports cdr car functions?
}

public static Object lamda( Object array, EvaluaterTransform ev )
throws
LamdaException
{
if( !array.getClass().isArray() &&
!array.getClass().getComponentType().
isPrimitive() ) {
throw new LamdaException( "Object must be primitive array,
was " +
array.getClass().getName() );
}
Object retValue = Array.newInstance( Object.class, Array.getLength(
array ) );
if( int.class == array.g
 
 
 

Multidimensional arrays and arrays of arrays

Post by Patricia S » Sat, 17 Jan 2009 04:12:14


...

You are right. I was being lazy. I'd started out with "Class<Object>",
got a compiler error, and accepted the first alternative Eclipse
suggested, rather than thinking through the simplest valid declaration.

Patricia
 
 
 

Multidimensional arrays and arrays of arrays

Post by Daniel Pit » Sat, 17 Jan 2009 06:55:17


There is no difference between a multidimensional array, and an array of
arrays. They are the same thing. Java provides a little syntactic sugar
for allocation a uniform array of arrays (of arrays etc...), but there
is no other difference, and no way to tell, other than testing each
element of every array of arrays.

--
Daniel Pitts' Tech Blog: < http://www.yqcomputer.com/ ;
 
 
 

Multidimensional arrays and arrays of arrays

Post by Arne Vaj » Sat, 17 Jan 2009 11:13:43


You can do new float[12] just fine.

Arne
 
 
 

Multidimensional arrays and arrays of arrays

Post by Arne Vaj » Sat, 17 Jan 2009 11:16:10


Or we can say that Java does not have multidimensional arrays.

Depending on ones definition of multidimensional array.

Arne