Reputation: 2515
I have an object o
which I know for fact that it is an array of something.
How do I iterate over ȯ
?
Object o;
if (o != null && o.getClass().isArray()) {
for (Object each : o) { // compile error, of course
System.out.println(each);
}
}
Upvotes: 1
Views: 3291
Reputation: 3354
Try this code.
Object o = null;
Iterator ite = ((Iterable)o).iterator();
while(ite.hasNext()){
Object itObj = ite.next();
}
Upvotes: 0
Reputation: 1670
try this code:
ArrayList<Array_Type> array= (ArrayList<Array_Type>) o;
Iterator iterator=array.iterator();
System.out.println(iterator.next());
Java have Iterator interface that can walk through an Collection
, so if your 'o' Object is an array, cast it into 'array' ArrayList
and iterate on it.
Upvotes: 0
Reputation: 494
cast it to an array, like this:
public static void main(String... args) {
Object o = new Object[]{"one", "two"};
if (o != null && o.getClass().isArray()) {
for (Object each : (Object[])o) { // no compile error, of course
System.out.println(each);
}
}
}
Upvotes: 3
Reputation: 32498
You have cast that object to array before iterate through it.
if (o != null && o.getClass().isArray()) {
Object[] temp (Object[] o)
for (Object each : temp) {
System.out.println(each);
}
}
Upvotes: 0