读源码可以了解作者的思路,以后也会影响自己写代码,高质量的代码是我们一致的追求
1.接口多实现
private static JsonMapper createJsonMapper() {
if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", null)) {
return new JacksonMapper();
}
else if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
return new Jackson2Mapper();
}
return new NotSupportedJsonMapper();
}
private static class JacksonMapper implements JsonMapper {
private org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
@Override
public String write(Object input) throws Exception {
return mapper.writeValueAsString(input);
}
@Override
public <T> T read(String input, Class<T> type) throws Exception {
return mapper.readValue(input, type);
}
}
private static class Jackson2Mapper implements JsonMapper {
private com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
@Override
public String write(Object input) throws Exception {
return mapper.writeValueAsString(input);
}
@Override
public <T> T read(String input, Class<T> type) throws Exception {
return mapper.readValue(input, type);
}
}
2.identityHashMap与hashmap区别
当HashMap内部维护的哈希表的容量达到75%时(默认情况下),会触发rehash,而rehash的过程是比较耗费时间的。所以初始化容量要设置成expectedSize/0.75 + 1的话,可以有效的减少冲突也可以减小误差。
所以,我可以认为,当我们明确知道HashMap中元素的个数的时候,把默认容量设置成expectedSize / 0.75F + 1.0F 是一个在性能上相对好的选择,但是,同时也会牺牲些内存。
参考:https://www.hollischuang.com/archives/2431
/**
* Map with primitive wrapper type as key and corresponding primitive
* type as value, for example: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(8);
/**
* Map with primitive type name as key and corresponding primitive
* type as value, for example: "int" -> "int.class".
*/
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap<>(32);