对于以下代码:
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
强制转换为Collection
或Object[]
取决于其类型。
答案 0 :(得分:3)
未内置。在处理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())) {
。