迭代对象

时间:2014-04-25 12:16:40

标签: java arrays object

我有一个对象o我知道这是一个事物的数组。 如何迭代ȯ

Object o;
if (o != null && o.getClass().isArray()) {
  for (Object each : o) {  // compile error, of course
    System.out.println(each);
  }
}

4 个答案:

答案 0 :(得分:2)

将它转换为数组,如下所示:

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);
        }
    }
}

答案 1 :(得分:0)

在迭代之前,您已将该对象强制转换为数组。

if (o != null && o.getClass().isArray()) {
  Object[] temp (Object[] o)
  for (Object each : temp) {  
    System.out.println(each);
  }
}

答案 2 :(得分:0)

试试这段代码:

ArrayList<Array_Type> array= (ArrayList<Array_Type>) o;
Iterator iterator=array.iterator();
System.out.println(iterator.next());

Java有Iterator界面,可以浏览Collection,所以如果你的&#39; o&#39;对象是一个数组,将其转换为&#39;数组&#39; ArrayList并对其进行迭代。

答案 3 :(得分:0)

试试这段代码。

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