You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现从二维Object数组收集Number类型元素的collectNums方法?

Fixing Your collectNums Method

Hey there! I spotted a couple of key issues in your code that are preventing it from collecting the Number elements correctly. Let's walk through what's wrong and how to fix it.

Issues in the Original Code

  • Incorrect elements added to the list: Right now, you're adding the loop indices j and i to your numbers list instead of the actual Number element from the array. That's why you'd get index values instead of the numbers you want.
  • Optional simplification: In Java 7 and later, you can use the diamond operator (<>) to simplify the ArrayList initialization—no need to repeat the generic type twice.

Corrected Code

import java.util.ArrayList;
import java.util.List;

public class NumberCollector {
    public static List<Number> collectNums(Object nrAry[][]) { 
        List<Number> numbers = new ArrayList<>(); // 使用菱形运算符简化泛型声明
        for(int i = 0; i < nrAry.length; i++) { 
            for(int j = 0; j < nrAry[i].length; j++) { 
                Object element = nrAry[i][j];
                if (element instanceof Number) { 
                    numbers.add((Number) element); // 添加实际的Number类型元素
                }
            }
        }
        return numbers; 
    }

    // 测试示例
    public static void main(String[] args) {
        Object[][] testData = {
            {10, "not a number", 3.14f, true},
            {new Long(100), 5.0, "string", Byte.valueOf("2")}
        };
        List<Number> result = collectNums(testData);
        System.out.println(result); // 输出: [10, 3.14, 100, 5.0, 2]
    }
}

What Changed?

  1. Added the correct element: Instead of adding loop indices, we now cast the verified Number element to Number and add it to the list. Since we already checked element instanceof Number, this cast is completely safe.
  2. Simplified ArrayList initialization: Using new ArrayList<>() lets the compiler infer the generic type from the variable declaration (List<Number>), making the code cleaner.
  3. Improved readability: Added a element variable to store nrAry[i][j], so we don't repeat the array access twice—small touch that makes the code easier to scan.

内容的提问来源于stack exchange,提问作者John_Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:38:14