迭代“Collection”或“数组”对象的常用方法

时间:2016-09-12 05:13:57

标签: java

对于以下代码:

if (Collection.class.isAssignableFrom(object)) {
  int index = 0;
  for (Object item : (Collection) object) {
    doWork(index);
  }
} else if (object.getClass().isArray()) {
  int index = 0;
  for (Object item : (Object[]) object) {
    doWork(index);
  }
} else {
    // do something else
}

有没有一种简洁的方法将两个块组合在一起所以我只需要一个if-block来处理Collection和array?我拥有if-block else-if-block的唯一原因是因为我必须将object强制转换为CollectionObject[]取决于其类型。

1 个答案:

答案 0 :(得分:3)

未内置。在处理for与处理数组时,编译器会为增强型Iterable循环发出不同的代码。

无论

  1. 复制循环(当然,循环的内容不需要重复;使用问题中所示的方法),或
  2. Object[]包裹在List<Object>中,例如通过Arrays.asList,或
  3. Iterable创建自己的Object[]包装器(带有关联的Iterator)。 (不是特别困难,Iterable只有一个非默认方法,Iterator只有两个。)
  4. 以下是#2的例子:

    Collection<Object> objectCollection = null;
    if (Collection.class.isAssignableFrom(object.getClass())) {
        objectCollection = (Collection<Object>) object;
    } else if (object.getClass().isArray()) {
        objectCollection = Arrays.asList((Object[]) object);
    } else {
        // do something else
    }
    if (objectCollection != null) {
        int index = 0;
        for (Object item : objectCollection) {
            doWork(index); // See note on question, slightly odd not using `item` here
                           // and not incrementing index in loop
        }
    }
    

    附注:您在.getClass()中遗失了if (Collection.class.isAssignableFrom(object.getClass())) {