Android中使用Map實現相同Key不同Value

參考網址: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的實現歸根結底就是數組和鏈表的使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章