JAVA高级教程-Java Map(6)


6、Map的使用

package Map01;

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

/**
 * Map接口的使用
 */
public class Demo01_HashMap {

    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("cn","中国");
        map.put("uk","英国");
        map.put("usa","美国");
        map.put("usa","美国1");

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


        //删除
        map.remove("usa");


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

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

        }

    }
}
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());

        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Leoon123

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值