Re: how to write array elements to console
Alex Hunsley wrote:
It can't be done this way, because you can't pass int array (int[]) into
a method expecting an Object. They just don't match.
Dzikus wrote:
What do you mean they don't match?
The following example compiles and works...
private void f(Object o){
System.out.println("Hello");
}
private void g(){
int[] ala = {1,2,3};
f(ala);
}
They do so match!
Dzikus, you're entirely correct. Array types are subtypes of Object, and can
be upcast without fear. Downcasting works if the Object happens to be an array
at runtime for the downcast.
What you did, testing the claim, exemplifies wise use of Usenet.
There's a lot of reflection and C++ idiom in your posted code, so I didn't
delve into it much. To answer your original question, how to print an array
from a method that takes an Object parameter:
Another poster suggested simply using the parameter's toString() method, which
you can do implicitly or explicitly.
private PrintWriter out;
....
public void foo( Object obj )
{
out.println( "Object: " );
out.println( obj );
}
If you don't like the way the arrays' toString() methods work, you can crack
arrays into a loop. This requires a check for each primitive type and Object
if you're avoiding complicated reflection:
public void foo( Object obj )
{
if ( obj instanceof Object [] )
{
Object [] oarr = (Object []) obj;
for( Object o : oarr )
{
out.println( o );
}
}
else if ( obj instanceof int [] )
{
int [] iarr = (int []) obj;
for ( int i : iarr )
{
out.println( i );
}
}
// ... byte, char, short, long, float, double
else
{
out.println( obj );
}
out.flush();
}
As another poster pointed out, in a type that you design a reasonable
implementation of toString() is important.
Even better is when you know that you'll use only arrays of a type that you
design (or subtype thereof). Then you can simplify to a static method of, say,
parent class Foo that can print values of Foo [] as you like. If the array
lister method calls each element's own toString() then the whole listing will
be sensible.
- Lew