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

如何在Cloud Firestore中获取数组指定下标的元素值

Cloud Firestore 数组指定下标元素获取方案

你已经成功获取到了对应文档的数组集合,直接调用ArrayList的get()方法传入目标下标即可取值,Java中集合下标默认从0开始计数,所以第二个元素对应下标为1。
为了避免空指针或下标越界崩溃,建议先做合法性校验,完整实现代码如下:

firebaseFirestore.collection("levels").document("data").get()
    .addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            // 可根据数组实际存储类型调整泛型,示例为String类型
            ArrayList<String> arrayList = (ArrayList<String>) task.getResult().get("images"); 
            // 先校验数组非空且长度满足取值要求
            if (arrayList != null && arrayList.size() >= 2) {
                // 下标1对应数组第二个元素
                String targetValue = arrayList.get(1);
                // 后续可直接使用targetValue变量
            }
        }
    });

补充说明:如果数组内存储的不是字符串类型,只需将代码中的ArrayList<String>替换为对应类型(比如ArrayList<Integer>对应整型数组)即可正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:57:03