JAVA-HashMap的插入,查询,遍历

1.HashMap需要使用迭代(Iterator)进行遍历。创建一个类Student,类方法getName():

HashMap hMap = new HashMap();

Student student1 = new Student(10, "s001", "hh", 120);//实例化类

Student student2 = new Student(10, "s002", "ww", 123);

hMap.put("1", student1);//插入hashmap

hMap.put("2", student2);

if (hMap.containsKey("2"))//根据key查询。contains(英文意思:包含)

{

System.out.println("找到了");

Student student = (Student) hMap.get("2");

System.out.println(student.getName());

} else

{

System.out.println("没找到");

}

Iterator iterator = hMap.keySet().iterator();//迭代

while (iterator.hasNext())//是否有下一个

{

String key = iterator.next().toString();//获取key

Student student = (Student) hMap.get(key);//获取Value

System.out.println("遍历:" + student.getName());

}

你可能感兴趣的:(JAVA-HashMap的插入,查询,遍历)