iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java案例之HashMap集合存储学生对象并遍历
  • 467
分享到

Java案例之HashMap集合存储学生对象并遍历

2024-04-02 19:04:59 467人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

一、需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历 分析: 1.定义学生类2.创建HashMap集合对象3.创

一、需求:创建一个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集合存储学生对象并遍历的文章就介绍到这了,更多相关HashMap存储对象并遍历内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java案例之HashMap集合存储学生对象并遍历

本文链接: https://www.lsjlt.com/news/144708.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作