Re: how to write array elements to console
Dzikus wrote:
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?
void f(Object obj) {
// optional test
if (! obj.getClass().isArray())
throw new IllegalArgumentException("not array");
if (obj instanceof int[]) {
int[] arr = (int[])obj;
...
} else if (obj instanceof long[]) {
long[] arr = (long[])obj;
...
} else if ...
...
else
throw new IllegalArgumentException("phphhbbbh!");
}
A slightly different approach might look like
void f(Object obj) {
String className = obj.getClass().getName();
if (className.charAt(0) != '[')
throw new IllegalArgumentException("not array");
switch (className.charAt(1)) {
case 'I':
int[] iarray = (int[])obj;
...
break;
case 'J':
long[] larray = (long[])obj;
...
break;
...
default:
throw new IllegalArgumentException("phphhbbbh!");
}
}
Still another approach would be to change the way the method
is defined. Instead of writing one method to handle every possible
type of array, write a method for each array type you care about
and let the compiler figure out which to call:
void f(int[] array) { ... }
void f(long[] array) { ... }
...
However, this approach only works if you actually know the array
type at compile time, that is, if you actually have an int[]
reference or a long[] reference or whatever at the point when you
make the call. If you really, truly have an Object reference and
nothing more, you need to make the determination at run time.
--
Eric Sosman
esosman@acm-dot-org.invalid