Map集合

Map集合

没有继承Collection接口,提供了key到value的映射。且该集合中不能包含相同的key,每个key只能映射一个value

实现类

HashMap类:不保证映射顺序,特别不保证顺序永久不变。允许使用null

TreeMap类:在集合中具有一定顺序。在添加,删除和定位时性能比HasMap差

建议:使用HasMap实现集合

import java.util.*;

public class Demo01 {
    public static void main(String[] args){
        Map<String,String> map=new HashMap<>();//创建Map对象,添加的元素为两个字符串
        map.put("123","你好吗");               //向Map集合中添加元素
        map.put("456","我很好");
        Set<String> set= map.keySet();        //构建Map集合中所有key的set集合
        Iterator<String> it=set.iterator();   //构建迭代器
        System.out.println("key值:");
        while(it.hasNext()){  //遍历输出Map集合的key值
            System.out.print(it.next()+" ");
        }
        Collection<String> coll= map.values(); //构建Map集合中所有value值
        it= coll.iterator();
        System.out.println("\nvalue值:");
        while(it.hasNext()){  //遍历输出Map集合的value值
            System.out.print(it.next()+" ");
        }
    }
}
/*
key值:
123 456 
value值:
你好吗 我很好
*/
posted @ 2021-12-12 21:12  valder-  阅读(38)  评论(0)    收藏  举报