Java Collection详解

发布时间:2023-05-20

一、Collection基础概念

Collection是Java中的集合类,是Java编程中经常使用的一个类。Collection Framework提供了一套接口和类,用于存储和操作对象的集合,可以将同一类型的对象存储在集合中,实现更加灵活的操作。Collection Framework提供了三种类型的集合:Set,List和Map。 Collection接口是Set、List和Queue的基本接口,它定义了一些通用的方法:add()、remove()、contains()、isEmpty()等。Set元素是唯一的,List元素是按照索引排序的,Map元素由键值对组成。Collection Framework提供了多种实现Collection接口的类,例如LinkedList、ArrayList、HashSet、TreeSet等。 Java中还有一种Iterator接口,用于遍历集合中的元素,它允许我们按照任意顺序遍历集合,而不需要关心集合的底层实现。

二、List详解

Java中的List是一种有序的集合,可以包含重复元素。List中元素的索引是固定的,支持按照索引获取元素、添加元素、删除元素、修改元素等操作。常见的List实现类有ArrayList、LinkedList、Vector等,其中ArrayList和LinkedList是最常用的。 ArrayList是基于数组实现的,可以高效地在任意位置插入、删除元素。但是需要保证数组的连续空间,因此ArrayList在频繁插入、删除元素时,性能会降低。 LinkedList是基于双向链表实现的,它在插入、删除元素时性能较好,但是在随机访问元素时性能较差。

三、Set详解

Set是一种不允许重复元素的集合,常见的实现类有HashSet、TreeSet等。HashSet是基于哈希表实现的,可以高效地添加、删除元素,但是元素的顺序是不确定的。TreeSet是基于TreeMap实现的,可以保证元素的有序性。

四、Map详解

Map是一种键值对形式的集合,每个元素实际上是一个key-value对。Map中key是唯一的,可以用key来获取对应的value。常见的实现类有HashMap、TreeMap等。HashMap是基于哈希表实现的,可以高效地添加、删除元素;而TreeMap基于红黑树实现,可以保证元素的有序性。

五、代码示例

1. List示例:

// ArrayList示例
List<String> arrayList = new ArrayList<>();
arrayList.add("apple");
arrayList.add("banana");
arrayList.add("orange");
System.out.println(arrayList.get(0)); // 输出结果为"apple"
// LinkedList示例
List<String> linkedList = new LinkedList<>();
linkedList.add("apple");
linkedList.add("banana");
linkedList.add("orange");
System.out.println(linkedList.get(0)); // 输出结果为"apple"

2. Set示例:

// HashSet示例
Set<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("orange");
System.out.println(hashSet.size()); // 输出结果为3
// TreeSet示例
Set<String> treeSet = new TreeSet<>();
treeSet.add("apple");
treeSet.add("banana");
treeSet.add("orange");
System.out.println(treeSet.size()); // 输出结果为3

3. Map示例:

// HashMap示例
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 1);
hashMap.put("banana", 2);
hashMap.put("orange", 3);
System.out.println(hashMap.get("apple")); // 输出结果为1
// TreeMap示例
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 1);
treeMap.put("banana", 2);
treeMap.put("orange", 3);
System.out.println(treeMap.get("apple")); // 输出结果为1