Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > how to write array elements to console

Reply
Thread Tools

how to write array elements to console

 
 
tam@lheapop.gsfc.nasa.gov
Guest
Posts: n/a
 
      12-13-2006
Dzikus wrote:
> Yeah, it's a great hint.
> But still I have somehow downcast from Object to array of specified
> type ...


It's not trivial to do this, but it's more tedious than difficult
to handle an arbitrary input object if you allow a
recursive solution.

I believe you are correct that you will have to do explicit downcasts
to each of the primitive types. You may also want to handle
arrays of objects specially (which will get you multi-dimensional
arrays of all types as well).

E.g.,

void method(Object o) {

if (o instanceof Object[]) {
Object[] oa = (Object[]) o;
for (Object ox: oa) method(ox);
} else if (o instanceof int[]) {
... process int array ..
} else if (o instanceof double[]) {
... handle all 7 primitive arrays explictly
} else {
... Handle a non-array Object
}
}

This is one example where it would be nice to have double-dispatch but
that's not available in Java. [Double dispatch would allow you to
select from among overloaded 'method's the one whose signature
matched the actual rather than the declared class of the argument.]

Regards,
Tom McGlynn

 
Reply With Quote
 
 
 
 
Dzikus
Guest
Posts: n/a
 
      12-13-2006
> If you really, truly have an Object reference and
> nothing more, you need to make the determination at run time.
>

This is what I am looking for. I suspect that in such powerfull
language like java it is possible to avoid those switch - cases with
downcasting.
How can I do such determination?

 
Reply With Quote
 
 
 
 
Eric Sosman
Guest
Posts: n/a
 
      12-13-2006
Dzikus wrote:
>> If you really, truly have an Object reference and
>> nothing more, you need to make the determination at run time.
>>

> This is what I am looking for. I suspect that in such powerfull
> language like java it is possible to avoid those switch - cases with
> downcasting.
> How can I do such determination?


In either of the ways I showed, or perhaps in some other
way I didn't think of: I'm only a user of Java, not a guru.
The documentation for java.lang.Class is likely to be helpful.

One way or another, you will need to determine the actual
class of the array your Object reference refers to. You said
you only cared about arrays of primitive types, which makes
things a little easier: There is a fixed number of primitive
types to check for, and writing the code for each of them (or
for the subset that interests you) may take you a few minutes
but doesn't require much ingenuity.

--
Eric Sosman
http://www.velocityreviews.com/forums/(E-Mail Removed)lid
 
Reply With Quote
 
Oliver Wong
Guest
Posts: n/a
 
      12-13-2006

"Dzikus" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) ups.com...
> Hello,
> I have following problem:
> Let's assume there is a function
> f(Object obj){
> ...
> }
> And if obj is an array (of some primitive types) I want to write
> elements to Sysytem.out
>
> For example if I have:
> int[] array = {1, 2, 3, 4};
> f(array);
>
> The expected result would be
> 1
> 2
> 3
> 4
> Does anybody knows how to do it?


Here's a solution that does not do any downcasting, nor use any switch
statement. However, it does use an exception for control flow, which is
somewhat frowned upon.

<SSCCE>
import java.lang.reflect.Array;

public class ArrayTest {
public static void main(String[] args) {
f(new int[] { 1, 2, 3 });
f(new byte[] { 4, 5, 6 });
f(new char[] { 'a', 'b', 'c' });
}

public static void f(Object o) throws IllegalArgumentException {
if (!o.getClass().isArray()) {
throw new IllegalArgumentException("Not an array.");
}
int index = 0;
try {
while (true) {
System.out.println(Array.get(o, index));
index++;
}
}
catch (ArrayIndexOutOfBoundsException aioobe) {
// do nothing
}
}
}

</SSCCE>

The issue is that I can't figure out how to get the length of the array
without performing a cast. The following does not work:

o.getClass().getField("length").getInt(o);

It throws a NoSuchFieldException, which surprises me, because I'm pretty
sure arrays have a field called "length". But maybe it has to do with the
fact that arrays are somewhat "magical" and not pure objects?

- Oliver


 
Reply With Quote
 
Dzikus
Guest
Posts: n/a
 
      12-13-2006
Thanks for help.
This is what I was looking for
Array length we can get using Array.getLength function.

import java.lang.reflect.Array;
class ArrayTest{
public static void f(Object o) {
Class c =o.getClass();
if(c.isArray()){
for(int i = 0; i < Array.getLength(o); ++i){
System.out.println(Array.get(o, i));
}
}
}

public static void main(String[] args) {
f(new int[] { 1, 2, 3 });
f(new byte[] { 4, 5, 6 });
f(new char[] { 'a', 'b', 'c' });
}
}

 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      12-13-2006
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
 
Reply With Quote
 
Oliver Wong
Guest
Posts: n/a
 
      12-13-2006
"Dzikus" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) ups.com...
>
> Array length we can get using Array.getLength function.


I can't believe I missed that function.

Oh well. Hooray for teamwork! =)

- Oliver


 
Reply With Quote
 
Alex Hunsley
Guest
Posts: n/a
 
      12-18-2006
Lew wrote:
> 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.


Whoops, my bad! That'll teach me to not double check....
lex
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
XML elements to JavaScript Array elements Conversion P XML 1 07-07-2006 09:08 PM
How to open a new console and write something out write printf() Peter Hansen C++ 1 08-24-2003 11:49 AM
How to open a new console and write something out write printf() Peter Hansen C Programming 1 08-24-2003 11:49 AM
Re: console mp3->wav decoder for $indows or GUI one which supports console Ben Finney Python 2 06-30-2003 05:43 AM



Advertisments