温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java的HashMap集合存储学生对象并遍历的方法

发布时间:2022-04-01 11:16:33 来源:亿速云 阅读:217 作者:iii 栏目:开发技术

这篇文章主要讲解了“Java的HashMap集合存储学生对象并遍历的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java的HashMap集合存储学生对象并遍历的方法”吧!

一、需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历

分析:

  • 1.定义学生类

  • 2.创建HashMap集合对象

  • 3.创建学生对象

  • 4把学生添加到集合中

  • 5.遍历集合

public class StudentDemo {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,Student> m=new HashMap<String,Student>();
        //添加键值对
        m.put("01",new Student("张三"));
        m.put("04",new Student("赵六"));
        m.put("02",new Student("李四"));
        m.put("03",new Student("王五"));
        //遍历集合
        Set<Map.Entry<String,Student>> s= m.entrySet();
        //遍历
        for (Map.Entry<String,Student> ss:s){
            //根据键值对对象获取值和key
            String key=ss.getKey();
           Student value=ss.getValue();
            System.out.println(key+","+value.getName());
        }
        System.out.println("------------------------");
        //方式二,通过键找值
        Set<String> m1=m.keySet();
        for (String key :m1){
             Student student =m.get(key);
            System.out.println(key+","+student.getName());
        }
    }
}

二、需求:创建一个HashMap集合,键是学生对象(Student),值是地址(String),存储三个键值对元素,并遍历分析:

  • 1.定义学生类

  • 2.创建HashMap集合对象

  • 3.创建学生对象,并把学生对象当作键值添加到集合

  • 4把地址字符串添加到集合中

  • 5.为了保证数据的唯一性,需要在学生类中重写hashCodeequals方法

  • 6.遍历集合

public class StudentDemo {
    public static void main(String[] args) {
        //创建集合对象
        Map<Student,String> m=new HashMap<Student,String>();
        //添加键值对
        m.put(new Student("张三",18),"上海");
        m.put(new Student("李四",19),"北京");
        m.put(new Student("王五",20),"上海");
        m.put(new Student("王五",20),"海南");
        //方式一
        //获取所有键值对的集合
        Set<Map.Entry<Student,String>> s=m.entrySet();
        //方式一、遍历
        for (Map.Entry<Student,String> mm:s){
            //通过键值对获取对应的值与键
            Student key=mm.getKey();
            String value=mm.getValue();
            System.out.println(key.getName()+","+key.getAge()+value);
        }
        System.out.println("---------------------------------");
        //方式二
        Set<Student> key=m.keySet();
        for (Student s1:key){
            String value=m.get(s1);
            System.out.println(s1.getName()+","+s1.getAge()+","+value);
        }
    }
}

感谢各位的阅读,以上就是“Java的HashMap集合存储学生对象并遍历的方法”的内容了,经过本文的学习后,相信大家对Java的HashMap集合存储学生对象并遍历的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI