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

如何创建ArrayList并通过循环处理实现卡牌游戏的颜色ID计数功能

实现逻辑
  • 首先确认colors列表元素与下标的对应关系,你示例里的colors下标0对应颜色ID-1、下标1对应颜色ID0,以此类推,计数规则就是玩家持有的颜色ID对应colors里的下标,buffer对应下标的数值加1
  • 先初始化长度为8、全为0的buffer列表
  • 遍历玩家持有的卡牌颜色ID,匹配到colors中的对应下标后更新buffer计数
基础实现代码

直接用ArrayList自带的indexOf方法找下标,适合数据量小的场景:

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

public class CardCountTest {
    public static void main(String[] args) {
        // 初始化颜色ID列表
        ArrayList<Integer> colors = new ArrayList<>(Arrays.asList(-1, 0, 1, 2, 3, 4, 5, 6));
        // 初始化玩家持有卡牌列表(Java变量名不能带空格,这里调整为playerProperties)
        ArrayList<Integer> playerProperties = new ArrayList<>(Arrays.asList(0, 4, 6));
        // 初始化计数buffer,填充8个0
        ArrayList<Integer> buffer = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            buffer.add(0);
        }
        // 遍历玩家卡牌做计数
        for (Integer cardColor : playerProperties) {
            int targetIndex = colors.indexOf(cardColor);
            // 校验下标合法性,避免数组越界异常
            if (targetIndex >= 0 && targetIndex < buffer.size()) {
                buffer.set(targetIndex, buffer.get(targetIndex) + 1);
            }
        }
        // 示例输入对应的输出为 [0, 1, 0, 0, 0, 1, 0, 1]
        System.out.println(buffer);
    }
}
优化方案

如果后续卡牌数量大,每次调用indexOf都要遍历colors列表性能较差,可以提前构建颜色ID到下标的映射表,查询效率更高:

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

public class OptimizedCardCount {
    public static void main(String[] args) {
        ArrayList<Integer> colors = new ArrayList<>(Arrays.asList(-1, 0, 1, 2, 3, 4, 5, 6));
        ArrayList<Integer> playerProperties = new ArrayList<>(Arrays.asList(0, 4, 6));
        ArrayList<Integer> buffer = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            buffer.add(0);
        }
        // 提前构建颜色ID到下标的映射
        HashMap<Integer, Integer> colorIndexMap = new HashMap<>();
        for (int i = 0; i < colors.size(); i++) {
            colorIndexMap.put(colors.get(i), i);
        }
        // 遍历计数
        for (Integer cardColor : playerProperties) {
            if (colorIndexMap.containsKey(cardColor)) {
                int targetIndex = colorIndexMap.get(cardColor);
                buffer.set(targetIndex, buffer.get(targetIndex) + 1);
            }
        }
        System.out.println(buffer);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:57:01