2011-11-25 123 views
2

可能重複:
Isn't it easier to work with foo when it is represented by the class ArrayList rather than the interface List?
Why are most of the examples using ArrayList爲什麼通常地圖<X, X> =新的HashMap <X, X>()而不是HashMap <X, X> = new HashMap <X, X>()?

爲什麼我們主要是做,這樣

Map<Integer, String> map = new HashMap<Integer, String>(); 

,而不是

HashMap<Integer, String> map = new HashMap<Integer, String>(); 

&同時實例化ArrayList(s)。

回答

8

較少打字,Map是該類的接口(與List相同),因此它比HashMap更容易傳遞Map,因爲功能相同,唯一的區別是實現。這通常在某些情況下完成(在某些情況下),當我們說出於某種原因,您認爲HashMap不是您想要的,並且您想要使用TreeMap時,但是在所有代碼中都存在HashMap參數並更改這些參數會很痛苦。如果你通過Map,你不需要改變任何東西,你的代碼可以更靈活。

+4

它不僅是從一種類型轉換到另一種(HashMap到TreeMap),而是支持多態。您應該依賴合同(接口)而不是對象的內部實現。 – ewernli

+2

@ewernli我知道我試圖舉一個例子,所以我想我錯過了這一點。 –

相關問題