Java学习Day11

2019-09-26  本文已影响0人  JayMeWangGL

今日学习内容总结


Map集合

特点:
  1、Map集合是一个双列集合,一个元素包含两个值(一个key,一个value)
  2、Map集合中的元素,key和value的数据类型可以相同也可以不同
  3、Map集合中的元素,key是不允许重复的,value可以重复
  4、Map集合中的元素,key和value是一一对应的

常用子类:

常用方法:

        HashMap<String,String> hashMap =new HashMap<>();
        hashMap.put("a","A");
        hashMap.remove("a");
        System.out.println(hashMap.get("b"));
        System.out.println(hashMap.containsKey("c"));
        Set<String> key = hashMap.keySet();
        System.out.println(key);
        Set<String> set = hashMap.keySet();
        for (String key : set) {
            String value = hashMap.get(key);
            System.out.println(key+"="+value);
        } 
        Set<Map.Entry<String, String>> entries = hashMap.entrySet();
        System.out.println(entries);
        Set<Map.Entry<String, String>> entries = hashMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            Map.Entry<String, String> entry1 = entry;
            System.out.println(entry1.getKey()+"="+entry1.getValue());
        }

使用HashMap存储自定义类型的键值:
  要保证key值唯一,需要重写自定义类的equals和hashCode方法

LinkedHashMap:存储有序的元素集合

Hashtable:键值都不能为null

public class mapTest {
    public static void main(String[] args) {
        System.out.println("输入一个字符串");
        Scanner scanner=new Scanner(System.in);
        String str = scanner.next();
        HashMap<Character,Integer> map=new HashMap<>();
        findChar(str,map);
    }

    private static void findChar(String str, HashMap<Character, Integer> map) {
        char[] chars = str.toCharArray();
        for (char c : chars) {
            if(map.containsKey(c)){
                Integer integer = map.get(c);
                map.put(c,integer+1);
            }
            else {
                map.put(c,1);
            }
        }
        System.out.println(map);
    }
上一篇 下一篇

猜你喜欢

热点阅读