如何实现从二维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
jandito yournumberslist instead of the actualNumberelement 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 theArrayListinitialization—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?
- Added the correct element: Instead of adding loop indices, we now cast the verified
Numberelement toNumberand add it to the list. Since we already checkedelement instanceof Number, this cast is completely safe. - Simplified ArrayList initialization: Using
new ArrayList<>()lets the compiler infer the generic type from the variable declaration (List<Number>), making the code cleaner. - Improved readability: Added a
elementvariable to storenrAry[i][j], so we don't repeat the array access twice—small touch that makes the code easier to scan.
内容的提问来源于stack exchange,提问作者John_Doe
相关产品推荐
相关产品推荐

