package base.map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* HashMap使用举例
*
* @author pengch
*
*/
public class HashMapExample {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Chinese", new Long(100000));
m1.put("English", new Long(20000));
m1.put("French", new Long(3000));
m1.put("Korean", new Long(400));
System.out.println("The HashMap holds " + m1.size() + " elements");
System.out.println("The keys are:");
// 因为Map的key不可能重复,所以,可以用Set数据结构来存储
Set keySet = m1.keySet();
Iterator ikey = keySet.iterator();
while (ikey.hasNext()) {
System.out.println("\t" + ikey.next());
}
System.out.println("The values are:");
// 因为Map的值有可能重复,所以不能用Set,要用Collection
Collection valueCol = m1.values();
Iterator ival = valueCol.iterator();
while (ival.hasNext()) {
System.out.println("\t" + ival.next());
}
// 根据key,取出特定的值
System.out.println("The value for Key \"Korean\" is "
+ m1.get("Korean").toString());
}
}
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* HashMap使用举例
*
* @author pengch
*
*/
public class HashMapExample {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Chinese", new Long(100000));
m1.put("English", new Long(20000));
m1.put("French", new Long(3000));
m1.put("Korean", new Long(400));
System.out.println("The HashMap holds " + m1.size() + " elements");
System.out.println("The keys are:");
// 因为Map的key不可能重复,所以,可以用Set数据结构来存储
Set keySet = m1.keySet();
Iterator ikey = keySet.iterator();
while (ikey.hasNext()) {
System.out.println("\t" + ikey.next());
}
System.out.println("The values are:");
// 因为Map的值有可能重复,所以不能用Set,要用Collection
Collection valueCol = m1.values();
Iterator ival = valueCol.iterator();
while (ival.hasNext()) {
System.out.println("\t" + ival.next());
}
// 根据key,取出特定的值
System.out.println("The value for Key \"Korean\" is "
+ m1.get("Korean").toString());
}
}