HashMap實作Map介面,內部實作使用Hash Table,讓您在常數時間內可以尋得key/value對。
所謂的key/value對,簡單的說,您將Map容器物件當作一個有很多間房間的房子,每個房間的門有一把鑰匙,您將物件儲存至房間中時,要順便擁有一把鑰匙,下次要取回物件時,就是根據這把鑰匙取得。
以一個簡單的例子來作說明:
package onlyfun.caterpillar; import java.util.*; public class HashMapDemo { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("caterpillar", "caterpillar's message!!"); map.put("justin", "justin's message!!"); System.out.println(map.get("justin")); System.out.println(map.get("caterpillar")); } }
在宣告Map型態時,您指定了key/value各自的型態,這邊都是宣告為String,也就是以String物件作為key物件的型態,而
value也是以String物件作為其型態。
使用Map的put()方法將物件存入,必須同時指定key/value,而要取回物件時,則指定key,程式的執行結果如下:
justin's message!!
caterpillar's message!!
|
HashMap是個被經常使用的物件,您可以參考下面幾個例子中HashMap的應用:
可以使用values()方法返回一個Collection物件,如果您需要一次选代Map中所有的物件,這會很有用,例如:
package onlyfun.caterpillar; import java.util.*; public class HashMapDemo { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("justin", "justin's message!!"); map.put("momor", "momor's message!!"); map.put("caterpillar", "caterpillar's message!!"); Collection collection = map.values(); Iterator iterator = collection.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
執行結果:
momor's message!!
justin's message!!
caterpillar's message!!
|
HashMap使用Hash
Table,因而它有自己的排序方式,如果您想要在选代所有的物件時,依照插入的順序來排序,則可以使用LinkedHashMap,它是HashMap
的子類,使用values()所返回的Collection物件,其內含物件之順序即為當初您加入物件之順序,例如:
package onlyfun.caterpillar;
import java.util.*; public class LinkedHashMapDemo { public static void main(String[] args) { Map<String, String> map = new LinkedHashMap<String, String>(); map.put("justin", "justin's message!!"); map.put("momor", "momor's message!!"); map.put("caterpillar", "caterpillar's message!!"); Collection collection = map.values(); Iterator iterator = collection.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
執行結果:
justin's message!!
momor's message!!
caterpillar's message!!
|
|
|