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());

}

    原文作者:Mr_馮
    原文地址: https://www.jianshu.com/p/cccb6961c080
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞