Java方法返回大于阈值的int数组结果重复问题求助
问题原因分析
你的代码返回全相同元素的核心原因是:每次找到符合条件的元素时,你都会创建一个新数组,并且把这个新数组的所有位置都赋值为当前元素d。这会直接丢弃之前收集到的所有元素,最终数组里只会保留最后一个符合条件的元素(也就是示例中的93)。
比如第一次遇到93时,你创建了长度为2的数组并把两个位置都设为93;接着遇到81,又创建长度为3的数组并把三个位置都设为81;直到最后一次遇到93,数组所有位置都会被设为93,自然就得到了全93的结果。
修复方案
有三种常见的修复方式,按需选择:
方式一:先计数再创建数组
先遍历原数组统计符合条件的元素数量,再创建对应长度的数组,最后填充元素:
public int[] getValuesAboveThreshold(int threshold) { int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 }; // 统计符合条件的元素数量 int count = 0; for (int d : a) { if (d > threshold) { count++; } } // 创建结果数组并填充 int[] result = new int[count]; int index = 0; for (int d : a) { if (d > threshold) { result[index++] = d; } } return result; }
方式二:使用动态列表(更简洁)
利用ArrayList动态收集元素,最后转换为数组:
import java.util.ArrayList; import java.util.List; public int[] getValuesAboveThreshold(int threshold) { int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 }; List<Integer> tempList = new ArrayList<>(); for (int d : a) { if (d > threshold) { tempList.add(d); } } // 将List转换为int数组 int[] result = new int[tempList.size()]; for (int i = 0; i < tempList.size(); i++) { result[i] = tempList.get(i); } return result; }
方式三:Java 8+ 流操作(最简洁)
用Stream API一步完成过滤和数组转换:
import java.util.Arrays; public int[] getValuesAboveThreshold(int threshold) { int[] a = new int[] { 58, 78, 61, 72, 93, 81, 79, 78, 75, 81, 93 }; return Arrays.stream(a) .filter(d -> d > threshold) .toArray(); }
内容的提问来源于stack exchange,提问作者cordesjan
相关产品推荐
相关产品推荐

