Collection接口
是Java集合框架的根接口,继承Iterable
接口。
所有的Collection
实现类都应该提供两个“标准”构造方法:1)默认构造器(无参),用于构造空集合;2)参数为Collection
类型的构造器,用于构造一个新集合,该集合包含指定集合(参数)中的元素。
如果一个实现类没有实现某个具体的方法,需要在方法体内抛出UnsupportedOperationException
异常。
// 比如AbstractList中的add()方法
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
集合框架中的很多方法都是通过equals
方法实现的,比如类ArrayList
中的contains(Object o)
方法最终会通过遍历List中所有元素,查看目标元素o是否与List中的某个元素相等。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
return indexOfRange(o, 0, size);
}
int indexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = start; i < end; i++) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = start; i < end; i++) {
if (o.equals(es[i])) { // 遍历查看是否存在相等元素
return i;
}
}
}
return -1;
}
常用子接口
1 List
实现类:ArrayList、Vector、LinkedList
2 Set
实现类:HashSet、TreeSet
所有方法
Modifier and Type | Method | Description |
---|---|---|
boolean | add(E e) | 集合中增加特定元素,当集合改变的时候返回true (所以对于Set 类当增加已有元素返回false ) |
boolean | addAll(Collection c) | 集合中增加c 中所有元素 |
void | clear() | 删除所有元素,执行后集合为空 |
boolean | contains(Object o) | 返回true ,如果集合中存在至少一个指定元素元素(通过Objects.equals(o, e) ) |
boolean | containsAll(Collection c) | 返回true ,如果集合中存在集合c 的所有元素 |
boolean | equals(Object o) | 返回true ,如果两个集合相等 |
int | hashCode() | 返回集合的哈希码,注意:当equlas 方法重写时,也要重写hashCode 方法 |
boolean | isEmpty() | 返回true ,如果集合中没有元素 |
Iterator | iterator() | 返回遍历集合中所有元素的迭代器 |
default Stream | parallelStream() | Returns a possibly parallel Stream with this collection as its source. |
boolean | remove(Object o) | 删除指定元素,在Set 中删除元素o ,在List 中删除index=o 的元素 |
boolean | removeAll(Collection c) | 删除集合c 中含有的元素 |
default boolean | removeIf(Predicate filter) | 删除符合条件的元素 |
boolean | retainAll(Collection c) | 保留集合c 中含有的元素 |
int | size() | 返回集合中元素数量 |
default Spliterator | spliterator() | Creates a Spliterator over the elements in this collection. |
default Stream | stream() | Returns a sequential Stream with this collection as its source. |
Object[] | toArray() | 以数组形式返回集合 |
default T[] | toArray(IntFunction generator) | Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array. |
T[] | toArray(T[] a) | 以数组形式返回集合,返回类型根据运行时类型确定 |