目录常见集合接口概述Collection
Map
Collection接口
Map接口
补充内容
常见集合接口概述
Java中包含许多集合接口。其中比较常见的主要是Collection接口和Map接口:
1.1 Collection
由单元素组成的集合。其比较常见的直接子接口是List、Set和Queue接口。
表1.1 Collection接口常用方法
编号方法原型解释备注
1boolean add(E e)往集合中添加元素e
2boolean addAll(Collection extends E> c)往集合中添加集合c此时集合c的元素必须是E子类对象
3boolean remove(Object o)将元素o从集合中移除
4boolean removeAll(Collection extends E> c)将集合c从集合中移除此时集合c的元素必须是E子类对象
5boolean containsAll(Collection> c)判断集合中是否含有集合c的所有元素判断时不考虑元素顺序
6boolean retainAll(Collection> c)求集合与集合c的交集
7void clear()将集合中的元素全部清空
8int size()计算集合长度
9boolean isEmpty()判断集合是否为空
10boolean contains(Object o)判断集合是否含有元素o
11Iterator iterator()得到集合的Iterator
12Object[] toArray()将集合转换为Object数组使用时注意将返回值类型转换
1.2 Map
由键值对组成的集合。其比较常见的直接实现类有HashMap、TreeMap和LinkedHashMap类。
表1.2 Map接口常用方法
编号方法原型解释备注
1V get(Object key)获取Map中key对应的值
2V put(K key,V value)将key-value这对键值对加入Map中
3void putAll(Map extends K,? extends V> m)将Map m加入Map中注意m的泛型
4V remove(Object key)将key索引的键值对从Map中移除
5void clear()清空Map
6int size()计算Map的长度
7boolean isEmpty()判断Map是否为空
8boolean containsKey(Object key)判断Map是否含有主键key
9boolean containsValue(Object value)判断Map是否含有值Value
10Set keySet()将Map的主键放入Set中并返回
11Collection values()将Map的值放入Collection中并返回
12Set> entrySet()将Map中每对键值对转换为键值对实体,并以Set的方式返回
Collection接口
Collection接口有三个比较常见的子接口:List、Set和Queue接口
2.1 List接口及其实现类
List接口有三个比较常见的实现类:LinkedList、ArrayList和Vector类。它们都按照元素的插入顺序来保存元素。ArrayList:用数组实现的List——随机存取效率高,增删效率低 轻量级。线程不安全。
LinkedList:用双向循环链表 实现的List——随机存取效率低,增删效率高。线程不安全。
Vector:用数组实现的List——重量级,占据更多的系统开销。线程安全。
表2.1 List接口常用方法
编号方法原型解释备注
1boolean addAll(int index,Collection extends E> c)指定集合c的添加起始位为index
2E get(int index)获取位置index对应的元素
3E set(int index, E element)设置位置index的元素
4void add(int index,E element)将元素element添加到index
5E remove(int index)移除index上的元素
6int indexOf(Object o)得到元素o首次出现的位置
7int lastIndexOf(Object o)得到元素o最后出现的位置
8 subList(int fromIndex, int toIndex)得到列表从fromIndex到toIndex的子列表ArrayList
Class ArrayList:底层使用数组实现。相对于数组的优点是自扩展长度,在元素个数超过本身所能存放的最大个数时能够自动扩展自身的长度。public ArrayList()、public ArrayList(Collection extends E> c)、public ArrayList(int initialCapacity):其中集合c是E子类的集合,用于在构造过程中初始化ArrayList;initialCapacity则表示待初始化的ArrayList初始长度。
public void trimToSize():释放列表的预留空间,使得列表所占空间尽量小。
public void ensureCapacity(int minCapacity):设定列表的最小长度。当minCapacity小于列表元素个数时,列表长度以列表元素个数为准。
public int lastIndexOf(Object o):返回元素o出现的最后一个位置序号
public E get(int index)、public E set(int index,E element):ArrayList的读写方法
protected void removeRange(int fromIndex, int toIndex):删除序号在fromIndex-toIndex之间的元素
public List subList(int fromIndex, int toIndex):得到从fromIndex-toIndex之间的元素列表
LinkedList
1.
c. VectorMap接口
补充内容