2013-03-13 85 views
-2

我是新來的Java和整個以下使用的包含HashMap傳來:地圖和HashMap在Java中

public static HashMap< String, Integer > Table1; 
.... 
Table1 = new HashMap< String, Integer >(); 

..... 
public Map<String, Integer> Table2 = new HashMap<String, Integer>(); 

我的問題是在上面的語句等同?我看到Map<String, Integer>用於表2。是HashMap< String, Integer > Table1Map<String, Integer> Table2相同的編程構造?它們可以互換使用嗎?

+0

這是很好的做法,[代碼交互(http://stackoverflow.com/questions/48605/why-do-most-system-architects-insist-on -first-coding-to-an-interface)(即你的第二個例子) – assylias 2013-03-13 03:37:15

+0

有一點不同,'Table1'是'static'。 – Mordechai 2013-03-13 04:13:40

回答

1

Map是接口,HashMap是從Map接口實現的類。

接口變量可以容納子類的引用。您不能互換使用。

2

Map是一個接口,而HashMap是它的一個實現。它們只能在一個方向上互換,這意味着在任何可以使用Map的地方,都可以使用HashMap代替。不過,因爲Map表示所有類型的「地圖」必須提供的所有操作,無論它是基於散列的地圖(HashMap),分類地圖(TreeMap),線程安全地圖(ConcurrentMap) ,或不可變的地圖(ImmutableMap from Guava)。任何這些不同類型的地圖,以及更多,都可以用於調用Map的任何地方。 Map本身不提供任何實際的工作代碼。它只說明每種地圖必須能夠做什麼。

瞭解有關此關係的更多信息,請參閱跟蹤中"What Is an Interface?"部分的Java教程以及"Interfaces and Inheritance"跟蹤中的關係。

1

根據定義,Table1必須始終是一個HashMap,但Table2也可以是其他映射。

public Map<String, Integer> Table2 = new HashMap<String, Integer>(); 
Table2 = new TreeMap<String, Integer>(); 
Table2 = someFunctionThatReturnsMaps(); 

最後一個可能是最重要的,因爲有多種,其回報,你將不得不轉換爲HashMap中的表1地圖類型的圖書館。

額外注:一般的慣例是有變量名開始小寫(表1,表2,等)