263 hashmap集合练习之:键是Student

263 hashmap集合练习之:键是Student

【需求】

创建一个HashMap集合,键是Student对象,值是String住址

存储多个键值对,并遍历

要求:如果学生对象的变量值相同,视为同一个对象

【思路】

1. 定义Student类,注意!要在Student类里重写2个方法(可快捷生成),保证学生的唯一性

---1-equals方法

---2-HashMap方法

2. 创建HashMap集合

3. 创建学生对象

4. 添加学生到集合的值

5. 遍历集合

--------------------------------------------------------------

package e263;

public class Student263 {

    private String name;

    private int age;

    public Student263(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 boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getclass() != o.getclass()) return false;

        Student263 that = (Student263) o;

        if (age != that.age) return false;

        return name.equals(that.name);

    }

    @Override

    public int hashCode() {

        int result = name.hashCode();

        result = 31 * result + age;

        return result;

    }

}

--------------------------------------------------------------

package e263;

import java.util.HashMap;

import java.util.Set;

public class HashMapDemo {

    public static void main(String[] args) {

        HashMap<Student263,String> jihe263 = new HashMap<Student263,String>();

        Student263 ss1 = new Student263("TRACY", 33);

        Student263 ss2 = new Student263("BEN", 70);

        Student263 ss3 = new Student263("CECILIA", 23);

        Student263 ss4 = new Student263("CECILIA",23);

        jihe263.put(ss1,"LONDON");

        jihe263.put(ss2,"PARIS");

        jihe263.put(ss3,"PEKING");

        jihe263.put(ss4,"TOKYO");

        //Student类里不重写equals and HashMap方法,则对象相同时,后加的对象叠加到集合里

        //Student类里重写equals and HashMap方法,则对象相同时,后加的对象替换先加的对象

        System.out.println("\t21.原始数据");

        System.out.println(jihe263);

        System.out.println("\t24.遍历并输出");

        Set<Student263> jianjihe = jihe263.keySet();

        for (Student263 jian : jianjihe){

            String zhi = jihe263.get(jian);

            System.out.println(jian.getName()+","+jian.getAge()+","+zhi);

        }

    }

}

--------------------------------------------------------------

21.原始数据

{e263.Student263@93f92e08=LONDON, e263.Student263@e879c27b=TOKYO, e263.Student263@1f0d3b=PARIS}

24.遍历并输出

TRACY,33,LONDON

CECILIA,23,TOKYO

BEN,70,PARIS

猜你喜欢

转载自blog.csdn.net/m0_63673788/article/details/121416157