编程语言
首页 > 编程语言> > java笔试题(四)

java笔试题(四)

作者:互联网

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Javatest87 {
    /**
     * 集合-Map(HashMap)、Collections工具类-map遍历
     * 练习1:班级有不同数量的学生,用map保存;循环取出学生信息
     * //学生类
     * class Stu{
     *     String id;
     *     String name;
     *     int age;
     *
     *     public Stu(String id, String name, int age) {
     *         this.id = id;
     *         this.name = name;
     *         this.age = age;
     *     }
     *
     *     public String getId() {
     *         return id;
     *     }
     *
     *     public void setId(String id) {
     *         this.id = id;
     *     }
     *
     *     public String getName() {
     *         return name;
     *     }
     *
     *     public void setName(String name) {
     *         this.name = name;
     *     }
     *
     *     public int getAge() {
     *         return age;
     *     }
     *
     *     public void setAge(int age) {
     *         this.age = age;
     *     }
     *
     *     @Override
     *     public String toString() {
     *         return "Stu{" +
     *                 "id='" + id + '\'' +
     *                 ", name='" + name + '\'' +
     *                 ", age=" + age +
     *                 '}';
     *     }
     */
    public static void main(String[] args) {
        HashMap<String,Stu> map = new HashMap<>();
        //创建学生对象
        Stu stu1 = new Stu("001","Luly",16);
        Stu stu2 = new Stu("002","Lily",16);
        Stu stu3 = new Stu("003","Tina",16);
        Stu stu4 = new Stu("001","Hulu",17);
        Stu stu5 = new Stu("002","Tom",15);
        //map添加元素
        map.put("一班学生1",stu1);
        map.put("一班学生2",stu2);
        map.put("一班学生3",stu3);
        map.put("二班学生1",stu4);
        map.put("二班学生2",stu5);
        //打印map元素
       //1、foreach遍历
        for (Map.Entry<String,Stu> entry:map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //2、Iterator
        Iterator<Map.Entry<String,Stu>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,Stu> entry = it.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //3、foreach遍历key、value
        for (String key:map.keySet()) {
            System.out.println("遍历map中key:" + key);
        }
        for (Stu stu:map.values()) {
            System.out.println("遍历map中value:" + stu);
        }
        //4、不使用泛型的遍历
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

}

 

标签:map,java,String,笔试,id,Stu,public,name
来源: https://www.cnblogs.com/yixiaobaitest/p/16099470.html