milan
milan

Reputation: 2515

Iterate over Object

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

Answers (4)

gasparms
gasparms

Reputation: 3354

Try this code.

Object o = null;
Iterator ite = ((Iterable)o).iterator();
while(ite.hasNext()){
     Object itObj = ite.next();
}

Upvotes: 0

Ahmad Vatani
Ahmad Vatani

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

Paul S
Paul S

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

Abimaran Kugathasan
Abimaran Kugathasan

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

Related Questions