Java集合框架
一、介绍
Java集合框架(Java Collection Framework)可以看作是一种容器(Container),是用来存储对象信息的。是定义在java.util包下的一组接口和实现类。每一个类背后都是一个数据结构。
Java集合类主要由Collection和Map派生出来。如下图所示,Collection又派生出三个接口List、Queue、Set。需要注意的是Map不是Collection的派生类。
Java大致就是List、Queue、Set、Map四种接口体系:
(1)List代表有序可重复集合;
(2)Set代表无序不可重复集合;
(3)Queue是队列集合;
(4)Map代表存储键值对(key-value)的集合。
数组和集合的区别:
(1)数组长度不可变化,无法保存具有映射关系的数据;集合类用于保存元素数量不确定的数据,还可以保存具有映射关系的数据。
(2)数据元素可以保存简单类型或者对象;集合只能保存对象。
(3)Arrays是操作数组的工具类;Collections是操作集合的工具类。
二、接口(Interfaces)
1 Collection
1.1 Collection常用方法
方法名 | 说明 |
---|---|
boolean add(E e) | 把元素e放入集合 |
void clear() | 删除集合中的所有元素 |
boolean isEmpty() | 判断集合是否为空 |
boolean remove(Object e) | 删除集合中的一个元素e(如果存在) |
int size() | 返回集合中的元素个数 |
Object[] toArray() | 返回一个装有所有集合元素的数组 |
1.1 Collection使用示例
代码如下():
/**
* Collection 方法的使用
* 1.boolean add(E e):
* Ensures that this collection contains the specified element (optional operation).
* 把元素e放入集合, 添加成功返回 true, 失败返回 false
* 2.void clear():
* Removes all of the elements from this collection (optional operation).
* 删除集合中的所有元素
* 3.boolean isEmpty():
* Returns true if this collection contains no elements.
* 判断集合是否为空, 集合为空返回 true, 不为空返回 false
* 4.boolean remove(Object e):
* Removes a single instance of the specified element from this collection, if it is present (optional operation).
* 删除集合中的元素e中的一个(如果存在). 删除成功返回 true, 失败返回 false
* 5.int size():
* Returns the number of elements in this collection.
* 返回集合中的元素个数
* 6.Object[] toArray():
* Returns an array containing all of the elements in this collection.
* 返回一个装有所有集合元素的数组
*/
public static void main(String[] args) {
Collection<Integer> collection = new ArrayList<>();
// 集合是否为空
System.out.println("集合是否为空: " + collection.isEmpty());// true
// 添加元素
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
collection.add(1);
// 集合是否为空
System.out.println("集合是否为空: " + collection.isEmpty());// false
// 打印集合元素
for (int i: collection) {
System.out.print(i + ", ");// 1,2,3,4,1
}
System.out.println();
// 集合元素数量
System.out.println("集合元素数量: " + collection.size());// 5
// 删除一个元素
System.out.println("是否删除成功: " + collection.remove(1));// true
System.out.println("是否删除成功: " + collection.remove(5));// false
// 删除集合中所有元素, 返回数组所有元素
System.out.println("clear 前: " + Arrays.toString(collection.toArray()));// [2,3,4,1]
collection.clear();
System.out.println("clear 后: " + Arrays.toString(collection.toArray()));// []
}
结果如下:
集合是否为空: true
集合是否为空: false
1, 2, 3, 4, 1,
集合元素数量: 5
是否删除成功: true
是否删除成功: false
clear 前: [2, 3, 4, 1]
clear 后: []
2. Map
2.1 Map常用方法
方法名 | 说明 |
---|---|
V get(Object k) | 根据k查找对应的value |
V getOrDefault(Object k, V defaultValue) | 根据k查找指定的value,没有找到用默认值代替 |
V put(K key, V value) | 将 key-value 放入Map |
boolean containsKey(Object key) | 判断是否包含key |
boolean containsValue(Object value) | 判断是否包含value |
Set<map, Entry<K,V>> entrySet() | 返回所有键值对 |
boolean isEmpty() | 判断是否为空j |
int size() | 返回键值对数量 |
2.2 Map使用示例
代码如下:
/**
* 1.V get(Object k):
* Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
* 根据k查找对应的 value, 存在相应的 key 就返回相应的 value
* 2.V getOrDefault(Object k, V defaultValue)
* Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
* 根据k查找指定的value,没有找到用默认值代替
* 3.V put(K key, V value)
* Associates the specified value with the specified key in this map (optional operation).
* 将 key-value 放入Map
* 4.boolean containsKey(Object key):
* Returns true if this map contains a mapping for the specified key.
* 判断是否包含key
* 5.boolean containsValue(Object value):
* Returns true if this map maps one or more keys to the specified value.
* 判断是否包含value
* 6.Set<map, Entry<K,V>> entrySet():
* Returns a Set view of the mappings contained in this map.
* 返回所有键值对
* 7.boolean isEmpty():
* Returns true if this map contains no key-value mappings.
* 判断是否为空
* 8.int size():
* Returns the number of key-value mappings in this map.
* 返回键值对数量
*/
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
// 判空
System.out.println("map是否为空" + map.isEmpty());// true
// 添加键值对
map.put("沈从文","边城");
map.put("雨果","悲惨世界");
map.put("紫金陈","坏小孩");
map.put("曹雪芹","红楼梦");
// 判空
System.out.println("map是否为空" + map.isEmpty());// false
// 返回键值对数量
System.out.println("键值对数量: " + map.size());// 4
// 打印所有键值对
System.out.println(map.entrySet());// [沈从文=边城, 雨果=悲惨世界, 紫金陈=坏小孩, 曹雪芹=红楼梦]
// 是否包含某个 key 或者 value
System.out.println(map.containsKey("沈从文"));// true
System.out.println(map.containsValue("西游记"));// false
// 如果不包含某个值就使用默认值嗲提
System.out.println(map.getOrDefault("吴承恩", "西游记"));// 西游记
// 当 key 相同时, 会覆盖原来的 value
map.put("紫金陈","无证之罪");
for (Map.Entry<String, String> entry: map.entrySet()) {
System.out.print(entry + " ");// 沈从文=边城 雨果=悲惨世界 紫金陈=无证之罪 曹雪芹=红楼梦
}
}
结果如下:
map是否为空true
map是否为空false
键值对数量: 4
[沈从文=边城, 雨果=悲惨世界, 紫金陈=坏小孩, 曹雪芹=红楼梦]
true
false
西游记
沈从文=边城 雨果=悲惨世界 紫金陈=无证之罪 曹雪芹=红楼梦
3. 接口以及实现类
接口 | 实现类 |
---|---|
List | ArrayList、LinkedList、Stack、Vector |
Queue | LinkedList、PriorityQueue |
Set | TreeSet、HashSet |
Map | TreeMap、HashMap |
3.1 List
List是有序可重复集合。这里的有序指的是有相对应的顺序索引(默认是元素的添加顺序),通过这个索引可以访问指定元素的位置。
(1)ArrayList
ArrayList是一个动态数组,内部以数组的形式保存集合元素,是List很典型的一个实现。ArrayList擅长随机访问,同时它时非同步的。
(2)LinkedList
LinkedList内部以链表的形式保存元素,所以不支持随机访问,但是插入和删除操作的性能比较好。
3.2 Set
Set集合是无序不可重复的,所以把两个相同的元素插入只会有一个元素(不可重复),而且插入元素顺序和弹出元素顺序不一定相同(无序)。
(1)HashSet
HashSet是Set集合最常用的实现类。HashSet按照hash算法来存储元素,因此存取和查找性能比较好
(2)TreeSet
TreeSet从图中明显看到实现了SortedSet,保证了元素的有序性。
就HashSet和TreeSet而言,HashSet的性能明显更好一些(特别是插入、查询元素)。因为TreeSet需要保证元素的有序,所以需要一个排序的 Set可以使用TreeSet
3.2 Map
Map采用键值对key-value的当时存储具有映射关系的数据,key和value可以是任何引用类型的数据。但是key值不允许重复,如果有重复的key,新添加的value会覆盖原来的value。
(1)HashMap
HashMap与Hashtable是Map接口的两个典型实现,它们的区别如下:
(1) HashMap是线程不安全,HashTable是线程安全的。
(2)HashMap可以使用null值作为key或value;HashTable不允许使用null值作为key和value,如果把null放进HashTable中,将会发生空指针异常。
为了成功的在HashMap和HashTable中存储和获取对象,用作key的对象必须实现hashCode()方法和equals()方法。
(2)TreeMap
TreeMap实现了SortedMap接口,是一个红黑树的数据结构,每个键值对作为红黑树的一个节点。TreeMap存储键值对时,需要根据key对结点进行排序。