java中如何实现哈希映射?
展开全部
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
class Student
{
String name;
int age;
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
}
public class HashMapTest
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
Student s1=new Student("Tom",21);
Student s2=new Student("Jerry",25);
Student s3=new Student("Lee",22);
Student s4=new Student("Lily",29);
hm.put("Tom",s1);
hm.put("Jerry",s2);
hm.put("Lee",s3);
hm.put("Lily",s4);
Student s=(Student)hm.get("Tom");
System.out.println("学生对象的名称为:"+s.name);
Set keySet=hm.keySet();
Iterator itr=keySet.iterator();
while(itr.hasNext())
{
String keys=(String)itr.next();
Student ss=(Student)hm.get(keys);
System.out.println("迭代输出学生对象的名称为;"+ss.name+"年龄为:"+ss.age);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询