要根据key获取ArrayList的值,可以使用HashMap来存储key-value对,其中key为ArrayList的索引,value为ArrayList中对应索引的值。

以下是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Value 1");
        arrayList.add("Value 2");
        arrayList.add("Value 3");

        HashMap<Integer, String> hashMap = new HashMap<>();
        for (int i = 0; i < arrayList.size(); i++) {
            hashMap.put(i, arrayList.get(i));
        }

        int key = 1; // 要获取值的索引
        String value = hashMap.get(key);
        System.out.println("Value at index " + key + ": " + value);
    }
}

在该示例中,我们创建了一个ArrayList并添加了三个值。然后,我们使用HashMap将ArrayList的索引作为key,ArrayList中对应索引的值作为value进行存储。最后,我们通过指定的key从HashMap中获取对应的值,并打印出来。

输出结果为:Value at index 1: Value

根据key获取arraylist的值

原文地址: https://www.cveoy.top/t/topic/idab 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录