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

如何向嵌套ArrayList中的Hand对象添加Card对象?

解决嵌套ArrayList的对象添加问题

我来帮你理清这个问题!你现在的核心需求是给Pile中指定索引的Hand添加一张Card,你的现有代码里有几个语法和逻辑错误,我们一步步来修正和理解:

首先修正基础类的语法和结构

你的原代码存在一些语法错误(比如类名、变量声明、构造方法写法),先把Hand和Pile类修正为合法的Java代码:

修正后的Hand类

public class Hand {
    // 注意这里是Card而不是Cards,匹配你的Card类命名
    private ArrayList<Card> hand;

    public Hand() {
        hand = new ArrayList<>(); // 用菱形语法简化泛型声明
    }

    // 封装添加卡片的方法,不直接暴露内部集合(面向对象最佳实践)
    public void addCard(Card card) {
        hand.add(card);
    }

    // 可选:如果需要获取手牌列表,提供只读或可控的访问方式
    public List<Card> getHand() {
        // 返回不可修改的列表,避免外部直接修改内部集合
        return Collections.unmodifiableList(hand);
    }
}

修正后的Pile类

public class Pile {
    private ArrayList<Hand> pile;

    public Pile() {
        pile = new ArrayList<>();
        // 初始化5个空的Hand对象
        for (int i = 0; i < 5; i++) {
            pile.add(new Hand());
        }
    }

    // 正确实现:给指定索引的Hand添加Card
    public void addToPile(int handIndex, Card card) {
        // 先检查索引合法性,避免越界异常
        if (handIndex < 0 || handIndex >= pile.size()) {
            throw new IndexOutOfBoundsException("指定的手牌索引超出范围:" + handIndex);
        }

        // 核心步骤:
        // 1. 从外层ArrayList中拿到目标Hand对象
        Hand targetHand = pile.get(handIndex);
        // 2. 调用Hand的addCard方法添加卡片
        targetHand.addCard(card);
    }
}

核心逻辑解释

你之前的错误在于混淆了外层集合的操作和内层对象的操作:

  • pile.add(...)是用来给Pile添加新的Hand对象的,不是用来添加Card的
  • 要给某个Hand加卡片,必须先通过pile.get(handIndex)拿到对应的Hand实例,再调用这个实例的方法来添加Card

可选:如果直接操作Hand内部集合(不推荐)

如果你不想封装addCard方法,一定要直接操作Hand里的ArrayList,可以在Hand中提供获取内部集合的方法(但这会破坏封装,不建议):

// 在Hand类中添加
public ArrayList<Card> getHand() {
    return hand;
}

然后Pile的addToPile方法可以写成:

public void addToPile(int handIndex, Card card) {
    if (handIndex >= 0 && handIndex < pile.size()) {
        // 直接调用内部ArrayList的add方法
        pile.get(handIndex).getHand().add(card);
    } else {
        throw new IndexOutOfBoundsException("指定的手牌索引超出范围:" + handIndex);
    }
}

但还是推荐用封装的方式,因为如果以后Hand的内部存储结构变化(比如换成LinkedList),外部代码不需要修改,只需要调整Hand的addCard方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:09:12