HashMap

HashMap實作Map介面,內部實作使用Hash Table,讓您在常數時間內可以尋得key/value對。

所謂的key/value對,簡單的說,您將Map容器物件當作一個有很多間房間的房子,每個房間的門有一把鑰匙,您將物件儲存至房間中時,要順便擁有一把鑰匙,下次要取回物件時,就是根據這把鑰匙取得。

以一個簡單的例子來作說明:

  • HashMapDemo.java
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中所有的物件,這會很有用,例如:

  • HashMapDemo.java
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物件,其內含物件之順序即為當初您加入物件之順序,例如:
  • LinkedHashMapDemo.java
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!!

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值