HashMap使用1

HashMapUse类:

package com.tiedandan.集合.Map集合.HashMap使用;

import java.util.HashMap;

public class HashMapUse {
    public static void main(String[] args) {
        HashMap<Student, String> students = new HashMap<>();//键类型是student,值类型是String类型
        Student stu1 = new Student("唐僧",1);
        Student stu2 = new Student("孙悟空",2);
        Student stu3 = new Student("猪八戒",3);
        Student stu4 = new Student("沙和尚",4);
        students.put(stu1,"天宫");
        students.put(stu2,"花果山");
        students.put(stu3,"高老庄");
        students.put(stu4,"流沙河");
        System.out.println("键值对个数:"+students.size());
        System.out.println("========输出键值对的值==========");
        System.out.println(students.toString());



    }
}

Student类:

package com.tiedandan.集合.Map集合.HashMap使用;

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

    public Student() {
    }

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

    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 "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

运行结果:

键值对个数:4
========输出键值对的值==========
{Student{name='猪八戒', age=3}=高老庄, Student{name='孙悟空', age=2}=花果山, Student{name='唐僧', age=1}=天宫, Student{name='沙和尚', age=4}=流沙河}

Process finished with exit code 0

posted on 2021-11-20 20:41  张铁蛋666  阅读(25)  评论(0编辑  收藏  举报

导航