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