Java进阶第四天

本文详细介绍了Java中的Map集合,包括HashMap、LinkedHashMap、Hashtable的特性与使用方法,以及如何利用Map进行字符串中字符计数的实战。还讨论了Map的of方法和调试技巧。此外,展示了如何在斗地主游戏中使用Map存储有序牌组。
摘要由CSDN通过智能技术生成

1、Map集合

1.1 Map
  (1)双列集合 Map<K,V> 一个元素包含两个值
  (2)两个泛型 键值对 类型可以不同 键唯一 键值一一对应
1.2 HashMap
  (1)底层是哈希表=数组+链表/红黑树,查询速度很快
  (2)HashSet集合new的是HashMap对象,但只使用了K值,所以不能存储相同元素
  (3)无序,不保证存取顺序一致
  (4)实现不同步,多线程,速度快
1.3 LinkedHashMap
哈希表+链表,多一条链表,保证元素有序(迭代顺序)
1.4 常用方法
  V put(K key, V value);//添加元素 返回V K不存在返回null,K已存在返回被替换的V
  V remove(Object key);//移除元素 返回V K不存在返回null,K存在返回被移除的V
  V get(Object key);
  boolean containsKey(Object key);
  Set keySet();//将Map集合中所有K取出来放在一个Set集合里
  Set<Map, Entry<K, V>> entrySet();
测试类
public class Demo04MapMethod {
  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();//多态
    //put方法
    String putV1 = map.put(“01”, “张三”);
    System.out.println(putV1);//null K不存在返回null
    String putV2 = map.put(“01”, “李四”);
    System.out.println(putV2);//张三 K已存在返回被替换的V
    System.out.println(map);//{01=李四} 重写了toString方法
    map.put(“02”, “王五”);
    map.put(“03”, “赵六”);
    map.put(“04”, “赵六”);//value可以一样
 
    //remove方法
    String removeV1 = map.remove(“04”);
    System.out.println(removeV1);//K存在,赵六
    String removeV2 = map.remove(“05”);
    System.out.println(removeV2);//K不存在,null
    System.out.println(map);//{01=李四, 02=王五, 03=赵六}
 
    Map<String, Integer> map2 = new HashMap<>();
    map2.put(“张三”, 178);
    map2.put(“李四”, 187);
    map2.put(“王五”, 185);
    System.out.println(map2);//{李四=187, 张三=178, 王五=185} 存取顺序可能不一致
 
    Integer removeV3 = map2.remove(“李四”);
    System.out.println(removeV3);//187
    System.out.println(map2);//{张三=178, 王五=185}
 
    int removeV4 = map2.remove(“张三”);//自动拆箱
    System.out.println(removeV4);//178
    System.out.println(map2);//{王五=185}
 
    // int removeV5 = map2.remove(“赵四”);//会抛出异常NullPointerException 空指针 因为不能将null赋值给int类型
    // System.out.println(removeV5);
    // System.out.println(map2);
 
    //get方法
    Integer getV1 = map2.get(“王五”);
    System.out.println(getV1);//185,K存在
    Integer getV2 = map2.get(“赵四”);
    System.out.println(getV2);//null,K不存在
 
    //containsKey方法
    boolean contains1 = map2.containsKey(“王五”);
    System.out.println(contains1);//true
    boolean contains2 = map2.containsKey(“赵四”);
    System.out.println(contains2);//false
 
    Map<String, Integer> map3 = new HashMap<>();
    map3.put(“坂田银时”, 68);
    map3.put(“冲田总悟”, 60);
    map3.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值