如何在Java中迭代嵌套Object数组并提取所有Integer元素?
嵌套Object数组提取所有Integer元素的解决方案
给定嵌套Object数组:
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
需要提取其中所有Integer元素,最终得到Integer[] = {1,2,3,4,5,6,7,8,9,10}。
你之前尝试的代码仅能获取顶层的Integer元素:
for(Object obj: array){ if(obj instanceof Integer) list.add((int)(obj)); }
原因是这段代码只处理了数组的第一层元素,没有遍历嵌套在子数组里的元素。要解决这个问题,需要通过递归逐层处理所有嵌套的子数组,具体实现如下:
import java.util.ArrayList; import java.util.List; public class NestedArrayProcessor { public static void main(String[] args) { Object[] nestedArray = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10}; List<Integer> integerList = new ArrayList<>(); // 调用递归方法提取所有Integer extractAllIntegers(nestedArray, integerList); // 将List转为Integer数组 Integer[] resultArray = integerList.toArray(new Integer[0]); // 验证结果 for (Integer num : resultArray) { System.out.print(num + " "); // 输出:1 2 3 4 5 6 7 8 9 10 } } private static void extractAllIntegers(Object[] arr, List<Integer> targetList) { for (Object element : arr) { if (element instanceof Integer) { // 是Integer则直接加入列表 targetList.add((Integer) element); } else if (element instanceof Object[]) { // 是子数组则递归处理 extractAllIntegers((Object[]) element, targetList); } } } }
核心逻辑说明
- 遍历数组中的每个元素,判断元素类型:
- 如果是
Integer类型,直接添加到结果列表; - 如果是
Object[]类型,递归调用提取方法处理该子数组,逐层深入所有嵌套层级;
- 如果是
- 最终将收集了所有Integer的List转为目标数组即可。
内容的提问来源于stack exchange,提问作者Dushyant Suthar
相关产品推荐
相关产品推荐

