Map集合-Map接口的实现类。

Map接口常用的实现类有HashMap和TreeMap。

HashMap类是基于哈希表的Map接口的实现,此实现提供所有可选的映射操作,并允许使用null值和null键,但必须保证键的唯一性。HashMap通过哈希表对其内部的映射关系进行快速查找。此类不保证映射的顺序。

TreeMap类不仅实现了Map接口,还是先了java.util.SortedMap接口。因此,集合中的映射关系具有一定顺序。但在添加、删除和定位映射关系时,就要比HahMap类的性能稍差。由于TreeMap类实现的Map集合中的映射关系是根据键对象按照一定的顺序排列的,因此不允许键对象是null。

import com.tmac.Map.jiekou.Stu;

import java.util.*;

public class MapTest {

    public static void main(String[] args) {

        // 1 . 由HashMap实现的Map对象。
        Map<String,String> map = new HashMap<>();
        // 2 . 创建添加对象。
        Stu stu1 = new Stu("351","张三");
        Stu stu2 = new Stu("512","李四");
        Stu stu3 = new Stu("853","王一");
        Stu stu4 = new Stu("125","赵六");
        Stu stu5 = new Stu("341","黄七");
        // 3 . 向集合里添加对象。
        map.put(stu4.getId(),stu4.getName());
        map.put(stu5.getId(),stu5.getName());
        map.put(stu1.getId(),stu1.getName());
        map.put(stu2.getId(),stu2.getName());
        map.put(stu3.getId(),stu3.getName());
        // 4 . 获取Map集合中的Key对象集合。
        Set<String> set = map.keySet();
        // 5 . 创建集合迭代器。
        Iterator<String> it = set.iterator();
        // 6 . 遍历Map集合。
        System.out.println("HashMap类实现的Map集合,无序:");
        while (it.hasNext()){
            String str = (String) it.next();
            /*
             * get(Object key)-----如果存在指定的key对象,则返回该对象对应的值,否则返回null。
             */
            String name = (String) map.get(str);
            System.out.println(str + " " + name);
        }
        // 7 . 由TreeMap实现的集合对象。
        TreeMap<String,String> treemap = new TreeMap<>();
        // 8 . 向集合里添加对象。
        treemap.putAll(map);
        /*
        keySet()-----返回该集合中的所有key对象形成的Set集合。
         */
        Iterator<String> iter = treemap.keySet().iterator();
        // 9 . 遍历TreeMap集合。
        System.out.println("TreeMap类实现的Map集合,键对象升序:");
        while(iter.hasNext()){
            // 10 . 获取集合中的所有key对象。
            String str = (String) iter.next();
            /*
            11 . 获取集合中的所有velues值。
            get(Object key)-----如果存在指定的key对象,则返回该对象对应的值,否则返回null。
             */
            String name = (String) treemap.get(str);
            System.out.println(str + " " + name);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值