浅谈List、Set和Map

一、List

有序,可重复。主要实现类有ArrayList、LinkedList和Vector

1. ArrayList

数组,查找效率高,可通过索引快速查找;增删效率低,从中间位置插入或删除时,需要对数组进行复制和移动,还需要更新索引。

AllayList不是线程安全的,多线程情况下使用会有问题

List<String> list = new ArrayList<>();

解决方案:

a. 使用Vertor集合

List<String> list1 = new Vector<>();

b. 使用集合类Collections的synchronizedList()方法

List<String> list2 = Collections.synchronizedList(new ArrayList<>());

c. 使用JUC中的CopyOnWriteArrayList类

List<String> list3 = new CopyOnWriteArrayList<>();

2. LinkedList

链表,插入和删除效率高,查询效率低

LinkedList也不是线程安全的,

List<String> linkedList = new LinkedList<>();

解决方案:

a. 使用集合类Collections的synchronizedList()方法

List<String> linkedList1 = Collections.synchronizedList(new LinkedList<>());

b. LinkedList换成ConcurrentLinkedQueue,我也没试过

List<String> linkedList2 = (List<String>) new ConcurrentLinkedQueue();

3. Vector

也是通过数组实现的,不同的是它支持线程的同步,某一时刻只有一个线程能写Vector,但实现同步效率没那么高,因此访问比ArrayList满

是线程安全的。

二、Set

无序,不可重复。主要实现类有HashSet

HashSet

不是线程安全的

Set<String> set = new HashSet<>();

解决方案:

a. 使用集合类Collections的synchronizedList()方法

Set<String> set1 = Collections.synchronizedSet(new HashSet<>());

b. 使用JUC中的CopyOnWriteArraySet类

Set<String> set2 = new CopyOnWriteArraySet<>();

三、Map

键值对形式,键唯一,值不唯一。主要实现类有HashMap和HashTable

1.HashMap

不是线程安全的

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

解决方案:

a. 使用集合类Collections的synchronizedMap()方法

Map<String, String> map1 = Collections.synchronizedMap(new HashMap<>());

b. 使用JUC中的ConcurrentHashMap类

Map<String, String> map2 = new ConcurrentHashMap<>();

2.HashTable

线程安全,效率低,用了synchronized,已过时。

不需要线程安全场景 可以用HashMap替换,需要线程安全场景可用ConcurrentHashMap替换。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值