集合接口的常见实现类

1、List接口的实现类

List接口的实现类最常用的有ArrayList和LinkedList、Vector

ArrayList: 实现了可变的数组,可以根据索引位置对集合进行快速的随机访问。

LinkedList: 采用链表结构保存对象,便于向集合中插入和删除对象,但是如果将元素插入到集合的尾部,其实ArrayList原比LinkedList快。

Vector: 也是List的一个常见实现类,但是在该类中的大多数方法都加了synchronized关键字,因此相比ArrayList、LinkedList集合在多线程访问时是线程的安全的。

2 、Set接口的实现类

Set接口的实现类常用的有HashSet和TreeSet、LinkedHashSet。它们的元素都不可重复。

HashSet:底层是哈希表,遍历元素和添加顺序、大小顺序无关。

TreeSet:底层是红黑树,元素按照大小顺序存储和遍历。

LinkedHashSet:底层是哈希表+双链表,遍历元素可以体现添加时顺序。顺序性是体现和HashSet不同之处。

3、Map接口的实现类

Map接口的实现类常用的有HashMap、LinkedHashMap和TreeMap。它们的key都不可重复。这里面的key不可重复 ,指的是容器中对于同一个Key只会存在一个。

HashMap:哈希表,底层是数组+链表+红黑树。遍历元素和添加顺序、大小顺序无关。

LinkedHashMap:哈希表+双链表,遍历元素可以体现添加顺序。

TreeMap:红黑树,元素按照key大小顺序存储和遍历。

例子(example):

package se.collect.map;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MapDemo1 {

    public static void main(String[] args) {
        System.out.println("input          1 : 1     3 : 3     2 : 2     4 : 4     5 : 5");
        //HashMap
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("1", "1");
        hashMap.put("3", "3");
        hashMap.put("2", "2");
        hashMap.put("4", "4");
        hashMap.put("5", "5");
        System.out.print("HashMap        ");
        for (String key : hashMap.keySet()) {
            System.out.print(key + " : " + hashMap.get(key) + "     ");
        }
        System.out.println();

        //LinkedHashMap
        Map<String, String> linkedHashMap = new LinkedHashMap<String, String>();
        linkedHashMap.put("1", "1");
        linkedHashMap.put("3", "3");
        linkedHashMap.put("2", "2");
        linkedHashMap.put("4", "4");
        linkedHashMap.put("5", "5");
        System.out.print("LinkedHashMap  ");
        for (String key : linkedHashMap.keySet()) {
            System.out.print(key + " : " + linkedHashMap.get(key) + "     ");
        }
        System.out.println();

        //TreeMap
        Map<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("1", "1");
        treeMap.put("3", "3");
        treeMap.put("2", "2");
        treeMap.put("4", "4");
        treeMap.put("5", "5");
        System.out.print("TreeMap        ");
        for (String key : treeMap.keySet()) {
            System.out.print(key + " : " + treeMap.get(key) + "     ");
        }
        System.out.println();
    }
}
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值