如果存在可以携带原始类型,通用数组和/或可迭代集合的
Java Collection实例,我想将通用数组视为Iterable集合,但是如何?例如以下伪java代码
- List<?> list1;
- list1.add(new int[2]);
- list1.add(new String[3]);
- list1.add(new ArrayList());
- for (Object e : list1){
- if (e instanceof Iterable){
- //The int[2] and String[3] will not fall in this case that I want it be
- //Iterate within e
- }
- }
请告知如何使int [2]和String [3]落在案例中.
谢谢&问候,
威廉
解决方法
在循环中,您可以为instanceof使用适当的数组操作数.
对于int []:
- if (e instanceof int[]) {
- // ...
- }
对于Object数组(包括String []):
- if (e instanceof Object[]){
- // ...
- }
或者,在将数组添加到主列表时,可以将每个数组包装在Arrays.asList()
中.在这种情况下,您可以使用List< List>通用而不是通配符通用List<?>并且避免使用instanceof检查数据类型.像这样的东西:
- List<List> list1;
- list1.add(Arrays.asList(new int[2]));
- list1.add(Arrays.asList(new String[3]));
- list1.add(new ArrayList());
- for (List e : list1){
- // no need to check instanceof Iterable because we guarantee it's a List
- for (Object object : e) {
- // ...
- }
- }
任何时候你一起使用instanceof和泛型,这是一种气味,你可能正在用你的泛型做一些不太正确的事情.