java集合类的继承图
Java的集合主要按两种接口分类:Collection、Map。
一、 Collection
1. Collection简介
1)Collection 接口有 3 种子类型集合: List、Set 和 Queue。
2)与数组的区别
数组 | 集合 | |
---|---|---|
长度 | 固定 | 可变 |
存储元素 | 基本类型/对象 | 对象 |
元素类型一致性 | 必须一致 | 可以不一致 |
3)Collection的主要方法
boolean add(Object o)添加对象到集合
boolean addAll(Collection c)将集合c中所有的元素添加给该集合
boolean remove(Object o)删除指定的对象
void removeAll(Collection c)从集合中删除c集合中也有的元素
boolean removeIf(Predicate<? super E> filter) 删除满足条件的所有元素
boolean contains(Object o)查找集合中是否有指定的对象
boolean containsAll(Collection c)查找集合中是否有集合c中的元素
Iterator iterator()返回一个迭代器
void retainAll(Collection c)从集合中删除集合c中不包含的元素
T[] toArray(T[] a) 将集合转换为T类型的数组
void clear()删除集合中所有元素
int size()返回当前集合中元素的数量
boolean isEmpty()判断集合是否为空
boolean equals( Object o) 将指定的对象与此集合进行比较已获得相等性
int hashCode() 返回此集合的哈希码值
Stream<E> stream() 返回类型是Stream<E>,返回以此集合作为源的顺序流
Spliterator<E> spliterator() 创建一个Spliterator在这个集合中。
注意:Spliterator(splitable iterator可分割迭代器)接口是Java为了并行遍历数据源中的元素而设计的迭代器,这个可以类比最早Java提供的顺序遍历迭代器Iterator,但一个是顺序遍历,一个是并行遍历。他是从java1.8的版本中开始加进去的。
4)Collection的遍历
a. collection继承自Iterable接口,可以使用Iterable中的forEach方法
b. 使用for-each
c. 使用Iterator迭代器x
@Test
public void collectionForEach() {
Collection<Integer> collection = Arrays.asList(1, 2, 3);
//第一种遍历方式:collection继承自Iterable接口,可以使用Iterable中的forEach方法
collection.forEach(System.out::println);
//第二种遍历方式:使用for-each
for(Integer i:collection){
System.out.println(i);
}
//第三种遍历方式:使用Iterator迭代器
Iterator<Integer> it = collection.iterator