java中使用Map时value存储具有常量池的基本数据类型(如Integer)遇到的问题

本文探讨了在Java中使用Map时,value为Integer类型可能导致的缓存问题,特别关注了127到-128范围内的值,并提供了针对这一现象的解决方案和对其他包装类的提示,帮助开发者解决LeetCode 242题的面试挑战。
摘要由CSDN通过智能技术生成

java中使用Map时value存储具有常量池的基本数据类型(如Integer)遇到的问题

今天刷leetcode 242.有效的字母异位词用到了两个map,map的value为Integer类型,本以为代码天衣无缝,却有一个测试用例不能通过。究其原因,想到了Integer在-128到127有缓存。

import java.util.HashMap;
import java.util.Map;

public class Se {
    public static void main(String[] args) {
        Map<Integer, Integer> map1 = new HashMap<>();
        Map<Integer, Integer> map2 = new HashMap<>();
        map1.put(1, 1024);
        map2.put(1, 1024);
        map1.put(2, 127);
        map2.put(2, 127);
        System.out.println(map1.get(1) == map2.get(1));
        System.out.println(map1.get(2) == map2.get(2));
        System.out.println(map1.get(1) == map1.get(1));
    }
}

输出结果如下
在这里插入图片描述
其他有缓存的包装类也会出现这种情况,希望能对大家有所帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用easyExcel导出,可以通过自定义转换器来实现将Integer类型的字典数据导出为具体的值。 首先,创建一个自定义转换器类,实现Converter接口,重写convertToExcelData和convertToJavaData方法,在convertToExcelData方法Integer类型的字典数据转换为具体的值,如下所示: ```java public class DictionaryConverter implements Converter<Integer> { private Map<Integer, String> dictionaryMap; public DictionaryConverter(Map<Integer, String> dictionaryMap) { this.dictionaryMap = dictionaryMap; } @Override public Class<?> supportJavaTypeKey() { return Integer.class; } @Override public CellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { String dictionaryValue = dictionaryMap.get(value); if (StringUtils.isNotBlank(dictionaryValue)) { return new CellData<>(dictionaryValue); } return new CellData<>(""); } @Override public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { return null; } } ``` 其,dictionaryMap是一个字典映射表,存储Integer类型的值与具体值之间的对应关系。 然后,在使用easyExcel进行导出,通过@ExcelProperty注解设置自定义转换器即可: ```java @ExcelProperty("状态") @Convert(converter = DictionaryConverter.class) private Integer status; ``` 这样,在导出Integer类型的字典数据就会被转换成具体的值了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值