Java教程

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

}

 

这篇关于java笔试题(四)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!