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

ArrayList质数统计实现咨询:方法头部初始化及主方法调用问题

统计ArrayList中质数数量(方法头部初始化ArrayList的实现)

我明白你想要的是不在方法体里初始化ArrayList,而是在方法头部(也就是调用方法的参数位置)完成初始化的实现方式,这其实很好实现——核心就是让统计质数的方法接收一个外部传入的ArrayList,把集合的初始化操作交给调用方,放在方法调用的参数里,完全避开方法体。

下面给你写一套完整的可运行代码,还有详细的调用说明:

import java.util.ArrayList;
import java.util.Arrays;

public class PrimeCounter {

    // 统计质数的方法:只负责处理传入的集合,不内部创建ArrayList
    public static int countPrimesInList(ArrayList<Integer> numberList) {
        int primeCount = 0;
        for (int num : numberList) {
            if (isPrime(num)) {
                primeCount++;
            }
        }
        return primeCount;
    }

    // 辅助方法:判断单个数字是否为质数,做了效率优化
    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        if (num == 2) { // 2是唯一的偶质数
            return true;
        }
        if (num % 2 == 0) { // 偶数直接排除
            return false;
        }
        // 只需要检查到数字的平方根,减少循环次数
        for (int i = 3; i <= Math.sqrt(num); i += 2) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        // 方式1:先初始化集合,再传入方法
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10));
        int count1 = countPrimesInList(numbers);
        System.out.println("方式1统计的质数数量:" + count1);

        // 方式2:直接在方法调用的参数位置初始化ArrayList(完美符合你的要求)
        int count2 = countPrimesInList(new ArrayList<>(Arrays.asList(11, 12, 13, 14, 15, 16, 17)));
        System.out.println("方式2统计的质数数量:" + count2);
    }
}

关键细节说明:

  • 方法头部初始化的核心:你要的“在方法头部初始化”其实就是方式2的写法——直接在调用countPrimesInList时,把new ArrayList<>(...)写在方法的参数括号里,也就是方法的“头部”区域,完全没有在方法体里创建集合。
  • 质数判断的优化:辅助方法isPrime排除了小于等于1的数、偶数,只检查奇数到平方根,比逐一遍历所有数效率更高。
  • 调用逻辑:Main方法里的两种方式都能用,方式2更贴合你的需求,直接在方法调用时完成集合初始化并传入。

运行这段代码后,方式1会输出4(对应的质数是2、3、5、7),方式2会输出3(对应的质数是11、13、17),完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:01:38