一、Collection介绍
1.为什么需要Collection
- Java是⼀⻔⾯向对象的语⾔,就免不了处理对象
- 为了⽅便操作多个对象,那么我们就得把这多个对象存储起来
- 想要存储多个对象(变量),很容易就能想到⼀个容器
- 常⽤的容器我们知道有-->StringBuffered,数组(虽然有对象数组,但是数组的⻓度是不可变的!)
- 所以,Java就为我们提供了集合(Collection)~
存储对象可以考虑:数组、集合
| 长度 | 元素的数据类型 | |
| 数组 | 固定 | 基本数据类型+存储引用类型 |
| 集合 | 可变 | 引用数据类型(存储的是简单的int,会自动装箱成Integer) |
2.总览


3.Collection的功能:
添加功能:
- boolean add(Object obj):添加一个元素;
- boolean addAll(Collection c):添加一个集合的元素;
删除功能:
- void Clear():移除所有的元素;
- boolean remove(Object obj):移除一个元素;
- boolean removeAll(Collection c):移除一个集合的元素,只要一个元素被移除了,就返回true;
判断功能:
- boolean contains(Object obj):判断集合是否包含该元素;
- boolean containsAll(Collection c):判断集合中是否包含指定的集合元素,只有包含所有的元素,才叫包含;
- boolean isEmpty():判断集合是否为空;
获取功能:
- Interator<E> iterator():迭代器
长度功能:
- int size():元素的个数;
交集功能:
- boolean retainAll(Collection c):移除此collection中未包含在指定collection中的所有元素。集合A和集合B做交集,最终的结果保存在集合A,返回值表示的是A是否发生过变化。
举例:
package 集合;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* ArrayList的常用方法
*
* @author nxf
* @since 2020-07-06
*/
public class TestCollection {
@Test
public void testCollection1(){
Collection col1 = new ArrayList();
// 1.size:返回集合中元素的个数
System.out.println(col1.size());
// 2.add(Object obj):向集合中添加一个元素
col1.add(123);
col1.add("AA");
col1.add(new Date());
col1.add("BB");
System.out.println(col1.size());
// 3.addAll(Collection col1);
Collection col2 = Arrays.asList(1,2,3);
col1.addAll(col2);
System.out.println(col1);
System.out.println(col1.size());
// 4.isEmpty():判断集合是否为空
System.out.println(col1.isEmpty());
// 5.clear():清空集合元素
col1.clear();
System.out.println(col1);
System.out.println(col1.isEmpty());
}
@Test
public void testCollection2(){
Collection col1 = new ArrayList();
col1.add(123);
col1.add("AA");
col1.add(new Date());
col1.add(new Person(25,"nxf"));
col1.add(new String("nxf"));
System.out.println(col1); // [123, AA, Mon Jul 06 15:10:37 CST 2020, 集合.TestCollection$Person@1b2a4, nxf]
// 6.contains(Object obj):判断集合中是否包含指定的obj元素,如果包含,返回true,否则,返回false
// 判断的依据:根据元素所在的类的equals()方法进行判断
// 明确:如果存入集合中的元素是自定义类的对象,要求:自定义类要重写equals()方法
System.out.println(col1.contains("Aa")); // false
boolean b1 = col1.contains(new Person(25,"nxf")); // Person类重写了equals方法
System.out.println(b1); // true
boolean b2 = col1.contains(new String("nxf")); // String重写了equals方法
System.out.println(b2); // true
// 7. containsAll(Collection col1)
Collection col2 = new ArrayList();
col2.add(123);
col2.add(new String("AA"));
boolean b3 = col1.containsAll(col2);
System.out.println(b3); // true
// 8.retainAll(Collection col1):求当前集合与col1的共有的元素,返回给当前集合
col1.retainAll(col2);
System.out.println(col1); // [123, AA]
// 9.remove(Object obj):删除集合中的obj元素,若删除成功,返回true,否则,返回false
boolean b4 = col2.remove("AA");
System.out.println(col2); // [123]
// 10.removeAll(Collection clo1):从当前集合中删除包含在col1中的元素
col1.removeAll(col2);
System.out.println(col1); // [AA]
// 11.equals(Object obj):判断集合中的所有元素是否完全相同
Collection coll2 = new ArrayList();
coll2.add(123);
coll2.add(new String("AA1"));
System.out.println(col2.equals(coll2)); // false
// 12.hashCode():
System.out.println(col1.hashCode()); // 2111
// 13.toArray():集合转化为数组
Object[] obj = col1.toArray();
for (int i=0;i<obj.length;i++){
System.out.println(obj[i]); // AA
}
// 14.asList():数组转化为集合
Collection col3 = Arrays.asList(1,2,3,4);
System.out.println(col3); // [1, 2, 3, 4]
// 15.iterator():返回一个Iterator接口实现类的对象,进而实现集合的遍历
Iterator iterator = col1.iterator();
// 方式1
for (int i=0;i<col1.size();i++){
System.out.println(iterator.next());
}
// 方式2
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
}
}
4.迭代器(Iterator)
Collection的源码中继承了Iterable,Iterable是⼀个接⼝,它有iterator()这个⽅法,返回的是Iterator也是⼀个接⼝,它只有三个⽅法:
- hasNext()
- next()
- remove()


可是,我们没能找到对应的实现⽅法,只能往Collection的⼦类下找找了,于是我们找到了--->ArrayList,于是,我们在ArrayList下找到了iterator实现的身影:它是在ArrayList以内部类的⽅式实现的!并且,从源码可知:Iterator实际上就是在遍历集合。
所以说:我们遍历集合(Collection)的元素都可以使⽤Iterator,⾄于它的具体实现是以内部类的⽅式实现的!
二、List集合
特点:
- 实现了Collection接口;
- List接口特性:是有序的,元素是可重复的;
- 允许元素为null。

Collection返回的是Iterator迭代器接⼝,⽽List中⼜有它⾃⼰对应的实现-->ListIterator接⼝该接⼝⽐普通的Iterator接⼝多了⼏个⽅法:

从⽅法名就可以知道:ListIterator可以往前遍历,添加元素,设置元素。
| 底层数据结构 | 是否线程安全 | 是否允许元素为null值 | |
| ArrayList | 数组 | 否 | 是 |
| LinkedList | 链表 | 否 | 是 |
| Vector | 数组 | 是 | 是 |
1.Vector
Vector是jdk1.2的类了,⽐较⽼旧的⼀个集合类。
- 底层结构是数组,初始容量为10,每次增长2倍;
- 它是线程同步的,已被ArrayList替代。
用ArrayList代替Vector:
- 在要求⾮同步的情况下,我们⼀般都是使⽤ArrayList来替代Vector的。
- 如果想要ArrayList实现同步,可以使⽤Collections的⽅法: List list =Collections.synchronizedList(new ArrayList(...)); // 就可以实现同步了
2.LinkedList
- 底层结构是双向链表;
- 实现了Deque接口,一次我们可以像操作栈和队列一样操作它;
- 线程非同步。

从结构上,我们还看到了LinkedList实现了Deque接⼝,因此,我们可以操作LinkedList像操作队列和栈⼀样。

2.1 构造方法
有两个构造方法

2.2 add方法
2.3 remove方法
2.4 get方法
2.5 set方法
3.ArrayList
- 底层结构是数组,初始容量为10,每次增长1.5倍;
- 在增删时候,需要数据的拷贝复制(navite方法由C/C++实现);
- 线程非同步。


ArrayList底层其实就是一个数组,ArrayList中有扩容这么一个概念,正因为它扩容,所以它能够实现“动态”增长。
3.1 构造方法

3.2 Add()方法

(1)add(E e)
步骤:
- 检查是否需要扩容;
- 插入元素;
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
3.3 get方法
3.4 set方法
3.5 remove方法
3.6 为什么ArrayList不是线程安全的,怎么解决?
为什么说ArrayList是线程不安全的?_Zorrooooo的博客-CSDN博客_arraylist线程安全吗
解决ArrayList线程不安全_ 木木不-CSDN博客_android 线程安全的list
4.CopyOnWriterArrayList
- 原理:在修改时,复制出一个新数组,修改的操作在新数组中完成,最后将新数组交由array变量指向;
- 写加锁,读不加锁;
- 缺点:CopyOnWriter容器只能保证数据的最终一致性,不能保证数据的实时一致性;
- 适合在读多写少的场景下使用。
三、Set集合
- 实现了Collection接口
- Set接口特性:无序的,元素不可重复;
- 底层大多数是Map结构的实现;
- 常用的三个子类都是非同步的。

| 底层数据结构 | 是否线程安全 | 是否允许有null值 | 备注 | |
| HashSet | 哈希表(一个元素为链表的数组)+红黑树 | 是 | ||
| TreeSet | 红黑树(一个自平衡的二叉树) | 是 | 保证元素的排序方式 | |
| LinkedHashSet | 哈希表+双向链表 | 否 |
1.HashSet
- 底层数据结构是哈希表(是一个元素为链表的数组)+红黑树
- 实际上就是封装了HashMap
- 元素无序,可以为null
2.LinkedHashSet
- 底层数据结构由哈希表(是一个元素为链表的数组)和双向链表组成;
- 父类是HashSet;
- 实际上就是LinkHashMap;
- 元素可以为null。
3.TreeSet
- 底层实际上是一个TreeMap实例(红黑树);
- 可以实现排序的功能;
- 元素不能为null。