Android中使用Map实现相同Key不同Value
程序员文章站
2024-03-23 15:54:40
...
参考网址:https://blog.csdn.net/lichunericli/article/details/89060052
public static void main(String[] args) {
Map<String, Object> identity = new IdentityHashMap<>();
identity.put("A", "A");
identity.put("A", "B");
identity.put("A", "C");
Map<String, Object> identityString = new IdentityHashMap<>();
identityString.put(String.join("A", ""), "B");
identityString.put("A", "A");
identityString.put(new String("A"), "C");
MultiValueMap<String, Object> linked = new LinkedMultiValueMap<>();
linked.add("A", "A");
linked.add("A", "B");
linked.add("A", "C");
for (String key : identity.keySet()) {
System.out.println("identity:" + identity.get(key));
}
for (String key : identityString.keySet()) {
System.out.println("identity string:" + identityString.get(key));
}
for (String key : linked.keySet()) {
System.out.println("linked:" + linked.get(key));
}
}
实现原理
JDK提供的IdentityHashMap其底层是根据Key的hash码的不同+transient Object[] table来实现的;
Spring提供的LinkedMultiValueMap其底层是使用LinkedHashMap来实现的;
LinkedHashMap的底层是使用transient Entry<K, V> head和transient Entry<K, V> tail来实现的;
Entry是LinkedHashMap的内部类,其定义方式为:
static class Entry<K, V> extends HashMap.Node<K, V> { Entry<K, V> before; Entry<K, V> after; }
总结
IdentityHashMap和LinkedMultiValueMap的实现归根结底就是数组和链表的使用。