Set,List,Map 集合

本文详细解析了Java中Map接口的概念及其实现,包括无序且不允许重复键的特性,以及通过三种集合视图查看内容的方式。文章还对比了HashMap与TreeMap的不同,并探讨了线程安全性的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述


Set:无序,元素不可重复(相对于元素的hashcode和equals来说)。
没重写hashCode()和hashCode()之前
这里写图片描述
在实体类中重写相关方法
这里写图片描述
重写后
这里写图片描述


An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

map是指某个对象的键和值有映射关系。一个map对象不能包含重复的键,每个键至多映射一个值。(但是若干键可以映射到一些相同的值。)


This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

Map接口替代了Dictionary类,Dictionary类是一个完全抽象类但却不是接口。

这里写图片描述


The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Map接口提供了三种集合视图(仅查看,Map本身不提供迭代器),允许map中的内容显示为set类型( keySet() )的键,collection类型的值( values() )或者set类型的键值对( entrySet() )。一些map的实现类,像TreeMap,可以对顺序有特殊的设定(排序器)。另一些,像HashMap则没有。

Map<Integer, Integer> tmap = new TreeMap<Integer,Integer>(new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);    //按键值降序
            //return o1.compareTo(o2);  //按键值升序(默认)
        }

    });

A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value.
特别需要注意的是不允许把map本身作为键,但是可以作为值。(应用场景是什么?)

Map可以存放Null值和Null键。

Map<Integer, Map<Integer, String> > map = new HashMap<Integer, Map<Integer, String>>();

TreeMap和HashMap都是非线程安全的
可以通过源码中方法是否有synchronized关键字看出,当然文档也有说明。
TreeMap:
TreeMap
HashMap:
这里写图片描述

HashTable线程安全
HashTable:
这里写图片描述

Ps:英语水平有限,望指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值