迭代Java中任何类型的泛型数组

前端之家收集整理的这篇文章主要介绍了迭代Java中任何类型的泛型数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果存在可以携带原始类型,通用数组和/或可迭代集合的 Java Collection实例,我想将通用数组视为Iterable集合,但是如何?例如以下伪java代码
  1. List<?> list1;
  2. list1.add(new int[2]);
  3. list1.add(new String[3]);
  4. list1.add(new ArrayList());
  5. for (Object e : list1){
  6. if (e instanceof Iterable){
  7. //The int[2] and String[3] will not fall in this case that I want it be
  8. //Iterate within e
  9. }
  10. }

请告知如何使int [2]和String [3]落在案例中.

谢谢&问候,
威廉

解决方法

在循环中,您可以为instanceof使用适当的数组操作数.

对于int []:

  1. if (e instanceof int[]) {
  2. // ...
  3. }

对于Object数组(包括String []):

  1. if (e instanceof Object[]){
  2. // ...
  3. }

或者,在将数组添加到主列表时,可以将每个数组包装在Arrays.asList()中.在这种情况下,您可以使用List< List>通用而不是通配符通用List<?>并且避免使用instanceof检查数据类型.像这样的东西:

  1. List<List> list1;
  2. list1.add(Arrays.asList(new int[2]));
  3. list1.add(Arrays.asList(new String[3]));
  4. list1.add(new ArrayList());
  5. for (List e : list1){
  6. // no need to check instanceof Iterable because we guarantee it's a List
  7. for (Object object : e) {
  8. // ...
  9. }
  10. }

任何时候你一起使用instanceof和泛型,这是一种气味,你可能正在用你的泛型做一些不太正确的事情.

猜你在找的Java相关文章