HashMap和HashSet

HashMap
Map中不允许有重复的键
Map接口有2个实现,分为
HashMap和TreeMap
TreeMap保存了数据的排列次序,HashMap不能。
HashMap本身是非线程安全的,但是collection框架提供方法可以保证HashMap是线程安全的。

put(key,value)添加键值对

HashSet
不允许集合中有重复值

add(Object o)添加对象

测试代码

public class Test {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        map.put(5, "e");
        HashMap<Integer, String> hmap = new HashMap<>();
        hmap.put(11, "aa");
        hmap.put(22, "bb");
        hmap.put(33, "cc");
        hmap.put(44, "dd");
        hmap.put(55, "ee");
        Set<String> set = new HashSet<>();
        set.add("1");
        set.add("2");
        set.add("3");
        set.add("3");
        //遍历treeMap
        for (Map.Entry<Integer, String> tm : map.entrySet()) {
            System.out.println(tm.getKey() + "---" + tm.getValue());
        }
        //遍历hashMap
        for (Map.Entry<Integer, String> hm : hmap.entrySet()) {
            System.out.println(hm.getKey() + "---" + hm.getValue());
        }


        System.out.println(set);
        //迭代器
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            //一次循环中iterator.next()方法不能出现两次,否则会报NoSuchElementException异常
            String next = iterator.next();
            if ("1".equals(next)) {
                System.out.println("找到了");
            }
        }
    }
}

控制台输出
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值