大可制作:QQ群:31564239(asp|jsp|php|mysql)

Java Gossip: 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!!