对于下面的代码:
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
}
是否有一种简洁的方法将两个 block 组合在一起,这样我只需要一个 if block 来处理 Collection 和数组?我拥有 if-block 和 else-if-block 的唯一原因是因为我必须将 object
转换为 Collection
或 Object[]
取决于其类型。
最佳答案
不是内置的。编译器为增强的 for
发出不同的代码处理 Iterable
时循环与处理数组相比。
要么
- 复制循环(当然,循环的内容不需要复制;使用问题中所示的方法),或者
- 包裹
Object[]
在List<Object>
,例如通过Arrays.asList
,或 - 创建您自己的
Iterable
Object[]
的包装(与关联的Iterator
)。 (不是特别困难,Iterable
只有一种非默认方法,Iterator
只有两种。)
这是#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())) {
.
关于java - 迭代 Collection 或数组对象的常见方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443706/