JAVA高级教程Java HashMap表达式(7)


7、HashMap的使用

students类

package Map01;

import java.util.Objects ;

public class Students implements Comparable<Students>{
    private String name;
    private  int stuNO;

    public Students() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getStuNO() {
        return stuNO;
    }

    public void setStuNO(int stuNO) {
        this.stuNO = stuNO;
    }

    @Override
    public String toString() {
        return "Students{" +
                "age='" + name + '\'' +
                ", stuNO=" + stuNO +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Students students = (Students) o;
        return stuNO == students.stuNO && Objects.equals(name, students.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, stuNO);
    }

    @Override
    public int compareTo(Students o) {
        int n1=this.name.compareTo(o.getName());
        int n2=this.stuNO-o.getStuNO();
        return n2;
    }
}
package Map01;

import Set01.Person;

import java.util.HashMap;
import java.util.Map;

public class Demo02_HashMap {
    public static void main(String[] args) {
        HashMap<Students,String> stu=new HashMap<>();


        Students p1=new Students("刘德华",20);
        Students p2=new Students("李小龙",22);
        Students p3=new Students("彭于晏",24);

        System.out.println("数据的个数"+stu.size());
        System.out.println(stu.toString());

        stu.put(p1,"上海");
        stu.put(p2,"北京");
        stu.put(p3,"深圳");
        //重写了hascode就不会重读
        stu.put(new Students("彭于晏",24),"深圳");


        System.out.println("数据的个数"+stu.size());
        System.out.println(stu.toString());


        //删除
        stu.remove(p1);


        //遍历
        //使用keyset
        System.out.println("============使用keyset======================");
//        Set<String> keys= map.keySet();
        for (Students key : stu.keySet()) {
            System.out.println(key+":"+stu.get(key));
        }

        //使用entryset遍历
        System.out.println("============使用entryset遍历======================");
//        Set<Map.Entry<String,String>> entries=map.entrySet();
        for (Map.Entry<Students, String> entry : stu.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());

        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leoon123

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值