import java.util.*;
//本程序演示 map 的使用,它的key 是 String,值是Employee类型
public class MapTset {
public static void main(String[]args)
{
Map<String,Employee> staff=new HashMap<String,Employee>();
staff.put("144-25-5464",new Employee("Amy Lee"));
staff.put("567-24-2546",new Employee("Harry Hacker"));
staff.put("157-62-7935",new Employee("Gary Cooper"));
staff.put("456-62-5527",new Employee("Francersca Cruz"));
// print all entries
System.out.println(staff);
//remove an entry
staff.remove("567-24-2546");
System.out.println("After remove Key:567-24-2546 :");
System.out.println(staff);
//replace an entry
staff.put("456-62-5527",new Employee("Francesca Miller"));
System.out.println("After replace Key:456-62-5527 :");
System.out.println(staff);
//iterate through all entries
System.out.println("Let have a iteration:");
for(Map.Entry<String,Employee> entry:staff.entrySet())
{
String key=entry.getKey();
Employee value=entry.getValue();
System.out.println("key="+key+",value="+value);
}
}
}
//mini employee class for test purpose
class Employee
{
public Employee(String n)
{
name=n;
salary=0;
}
public String toString()
{
return "[name="+name+",salary="+salary+"]";
}
private String name;
private double salary;
}
运行结果:
{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francersca Cruz,salary=0.0], 567-24-2546=[name=Harry Hacker,salary=0.0]}
After remove Key:567-24-2546 :
{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francersca Cruz,salary=0.0]}
After replace Key:456-62-5527 :
{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francesca Miller,salary=0.0]}
Let have a iteration:
key=157-62-7935,value=[name=Gary Cooper,salary=0.0]
key=144-25-5464,value=[name=Amy Lee,salary=0.0]
key=456-62-5527,value=[name=Francesca Miller,salary=0.0]
进程已结束,退出代码0