灵感来源
https://blog.youkuaiyun.com/u010648555/article/details/89390250
预计实现效果
- 原来map可以实现的功能
- String类型key相同的value以“–”间隔进行追加
- Integer类型key相同的value进行相加
- 可以扩展对key相同对value进行操作
实现
import java.util.HashMap;
/**
* @Description:
* @Date:2019-04-22 10:57
* @Version:
**/
public class MyHashMap<K,V> extends HashMap<K,V> {
/**
* key相同 String类型追加
*/
public V putString(K key,V value){
V newV = value;
if(containsKey(key)){
V oldv = get(key);
newV =(V)(oldv+"--"+newV);
}
return super.put(key, newV);
}
/**
* key相同 Integer类型相加
*/
public V putInteger(K key,V value){
V newV = value;
if(containsKey(key)){
V oldv = get(key);
newV =(V)(Integer.valueOf((Integer) oldv+(Integer) newV));
}
return super.put(key, newV);
}
}
测试
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date:2019-04-22 09:56
* @Version:
**/
@RestController
@RequestMapping("/test")
public class TestMap {
@RequestMapping("/testmap")
public MyHashMap test(){
MyHashMap map = new MyHashMap<>();
map.put("test1","11");
map.put("test1","22");
map.put("test1","33");
System.out.println(map.get("test1"));
return map;
}
@RequestMapping("/testmap2")
public MyHashMap test2(){
MyHashMap map = new MyHashMap();
map.putString("test1","11");
map.putString("test1","22");
map.putString("test1","33");
System.out.println(map.get("test1"));
return map;
}
@RequestMapping("/testmap3")
public MyHashMap test3(){
MyHashMap map = new MyHashMap();
map.putInteger("test1",1);
map.putInteger("test1",2);
map.putInteger("test1",3);
System.out.println(map.get("test1"));
return map;
}
}
测试结果



本文介绍了一种自定义的HashMap实现,该实现对于相同key的String类型value使用“--”进行连接,而Integer类型则进行相加。通过继承Java标准库中的HashMap并重写put方法,实现了对特定类型的value进行定制化的处理。
1327

被折叠的 条评论
为什么被折叠?



