博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
不要使用Integer做HashMap的key,尤其在json序列化的时候
阅读量:4630 次
发布时间:2019-06-09

本文共 1398 字,大约阅读时间需要 4 分钟。

使用redisson cache来实现一个缓存功能,缓存省市县的名称,key是区域编码,integer,value是name。结果取的时候,怎么都取不出。

Map
regionsMapregionsMap.get(110000) == null;

找了半天问题才发现regionsMap的key都是字符串。

for (Map.Entry
entry : regionsMap.entrySet()) { int code = entry.getKey(); String name = entry.getValue(); String s = regionsMap.get(code); System.out.println(s);}

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

我加入缓存的时候明明是Integer做为key的,清空缓存直接调用没问题,当从缓存取出来fan序列化后就变成了String key.

redisson采用JsonJacksonCodec反序列化时,是用Object作为对象decode.

private final Decoder decoder = new Decoder() {        @Override        public Object decode(ByteBuf buf, State state) throws IOException {            return mapObjectMapper.readValue((InputStream) new ByteBufInputStream(buf), Object.class);        }    };

这个会默认把key设置成string。

测试

@Testpublic void testMap() throws IOException {    ObjectMapper mapper = new ObjectMapper();    HashMap
map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); String s = mapper.writeValueAsString(map); //{"1":"a","2":"b"} System.out.println(s); HashMap o = (HashMap)mapper.readValue(s, Object.class); assertEquals(o.get("1"), "a"); assertNotEquals(o.get(1), "a");}

因此,不要用Integer做为key,如果你想使用Json序列化。

在使用json缓存的时候,同样不要将Integer当作HashMap的key类型。

转载于:https://www.cnblogs.com/woshimrf/p/do-not-use-integer-as-hashmap-key.html

你可能感兴趣的文章
测试用例设计方法基础理论知识
查看>>
基于visual Studio2013解决面试题之0804复杂链表
查看>>
find_in_set
查看>>
【转帖】SQLServer登录连接失败(error:40-无法打开到SQLServer的连接)的解决方案...
查看>>
ibatis的there is no statement named xxx in this SqlMap
查看>>
系统启动时,spring配置文件解析失败,报”cvc-elt.1: 找不到元素 'beans' 的声明“异常...
查看>>
《Python学习手册》读书笔记
查看>>
简单数据结构(队列 栈 树 堆 )
查看>>
洛谷P2380 狗哥采矿
查看>>
learning to openstack concept
查看>>
Kindeditor学习中的那些坑
查看>>
Servlet
查看>>
一篇价值百万的文章:我为什么在22岁辞去年薪150万的工作?
查看>>
信息安全系统设计基础期末总结
查看>>
leetcode 203 Remove Linked List Elements
查看>>
TCP/IP 笔记 1.3 IP:网际协议
查看>>
HDU 1061 Rightmost Digit
查看>>
八种简易健康减肥瘦身法
查看>>
win7旗舰版下配置IIS服务器
查看>>
web开发基础
查看>>