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

如何从LinkedHashMap拆分键值为数组并按索引取值?报错求助

问题解决:LinkedHashMap按索引获取键/值的错误修正

错误原因分析

你在getLHMValue方法中犯了类型不匹配的错误:

  • 调用lhm.entrySet()得到的是Map.Entry<Integer, Long>类型的集合,每个元素是完整的键值对,而非单独的值。
  • 当你尝试将这些Entry对象存入Integer[]数组时,由于类型不兼容,直接触发java.lang.ArrayStoreException。

修正后的代码实现

按索引获取值

使用Map.values()方法直接获取值的集合,再转换为支持索引访问的结构:

public static Integer getLHMValue(Map<Integer, Long> lhm, int index) {
    // 获取LinkedHashMap的有序值集合
    Collection<Long> valueCollection = lhm.values();
    List<Long> valueList = new ArrayList<>(valueCollection);
    
    // 校验索引合法性
    if (index < 0 || index >= valueList.size()) {
        throw new IndexOutOfBoundsException("索引超出集合范围:" + index);
    }
    
    // 将Long类型转换为Integer返回
    return valueList.get(index).intValue();
}

按索引获取键

keySet()的用法是正确的,转换为ArrayList简化索引访问,并增加合法性校验:

public static Integer getLHMKey(Map<Integer, Long> lhm, int index) {
    Set<Integer> keySet = lhm.keySet();
    List<Integer> keyList = new ArrayList<>(keySet);
    
    // 校验索引合法性
    if (index < 0 || index >= keyList.size()) {
        throw new IndexOutOfBoundsException("索引超出集合范围:" + index);
    }
    
    return keyList.get(index);
}

额外说明

  1. 有序性保证:LinkedHashMap的keySet()、values()、entrySet()都会保留插入顺序,因此按索引访问的结果符合预期。
  2. 数组方式替代(可选):如果偏好使用数组,可将List替换为数组转换,注意类型匹配:
// 获取值的数组版本
public static Integer getLHMValue(Map<Integer, Long> lhm, int index) {
    Long[] valueArray = lhm.values().toArray(new Long[0]);
    if (index < 0 || index >= valueArray.length) {
        throw new IndexOutOfBoundsException("索引超出集合范围:" + index);
    }
    return valueArray[index].intValue();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:45:44