【Java】HashMap集合存入学生对象

使用HashMap存入学生对象

  1. 定义学生Student实体类 成员属性 姓名、年龄
  2. 定义HashMap集合存入Student对象,key存放学号 value存放学生对象
  3. 这样做,可以保证学号不允许重复的

示例代码

package com.collection.Demo10;

public class Student {
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
package com.collection.Demo10;

import java.util.HashMap;

public class Test01 {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap<>();
        hashMap.put("mayikt01", new Student("张三", 22));
        hashMap.put("mayikt02", new Student("李四", 18));
        hashMap.put("mayikt03", new Student("王五", 24));
//        hashMap.put("mayikt03", new Student("张三", 24));//虽然key是不允许重复,但是会替换Value
        for (String key : hashMap.keySet()) {
            Student student = hashMap.get(key);
            System.out.println("学号:" + key + " 姓名:" + student.getName() + " 年龄:" + student.getAge());
        }
    }
}

下一篇文章:

你可能感兴趣的:(集合,HashMap,java,开发语言,HashMap)