1. ArrayList
在集合框架中,ArrayList是一个普通的类,实现了List接口,具体框架图如下:
-
ArrayList是以泛型方式实现的,使用时必须要先实例化
-
ArrayList实现了RandomAccess接口,表明ArrayList支持随机访问
-
ArrayList实现了Cloneable接口,表明ArrayList是可以clone的
-
ArrayList实现了Serializable接口,表明ArrayList是支持序列化的
-
和Vector不同,ArrayList不是线程安全的,在单线程下可以使用,在多线程中可以选择Vector或者CopyOnWriteArrayList
-
ArrayList底层是一段连续的空间,并且可以动态扩容,是一个动态类型的顺序表
2. ArrayList的使用
2.1 构造方法
方法 | 解释 |
---|---|
ArrayList() | 无参构造 |
ArrayList(Collection<? extends E> c) | 利用其他 Collection 构建 ArrayList |
ArrayList(int initialCapacity) | 指定顺序表初始容量 |
//private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//无参构造,数组长度为0 -> 为什么长度为0,也可以add成功?
}
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];//长度大于0,给多大分配多大
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;//数组长度为0,空数组
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);//小于0,抛异常
}
}
public ArrayList(Collection<? extends E> c) {//实现了Collection接口都可以进行传递,<? extends E>传的必须是E或者E的子类
//Collection<? extends E> c
// 类型 变量
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
public static void main(String[] args) {
// ArrayList创建,推荐写法
// 构造一个空的列表
List<Integer> list1 = new ArrayList<>(); //使用接口实现,可用方法只有List接口的方法
// 构造一个具有10个容量的列表
List<Integer> list2 = new ArrayList<>(10);
list2.add(1);
list2.add(2);
list2.add(3);
// list2.add("hello"); // 编译失败,List<Integer>已经限定了,list2中只能存储整形元素
// list3构造好之后,与list中的元素一致
ArrayList<Integer> list3 = new ArrayList<>(list2);
// 避免省略类型,否则:任意类型的元素都可以存放,使用时将是一场灾难
List list4 = new ArrayList();
list4.add("111");
list4.add(100);
}
2.2 ArrayList常见操作
方法 | 解释 |
---|---|
boolean add(E e) | 尾插 e |
void add(int index, E element) | 将 e 插入到 index 位置 |
boolean addAll(Collection<? extends E> c) | 尾插 c 中的元素 |
E remove(int index) | 删除 index 位置元素 |
boolean remove(Object o) | 删除遇到的第一个 o |
E get(int index) | 获取下标 index 位置元素 |
E set(int index, E element) | 将下标 index 位置元素设置为 element |
void clear() | 清空 |
boolean contains(Object o) | 判断 o 是否在线性表中 |
int indexOf(Object o) | 返回第一个 o 所在下标 |
int lastIndexOf(Object o) | 返回最后一个 o 的下标 |
List subList(int fromIndex, int toIndex) | 截取部分 list |
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("JavaSE");
list.add("JavaWeb");
list.add("JavaEE");
list.add("JVM");
list.add("测试课程");
System.out.println(list);
// 获取list中有效元素个数
System.out.println(list.size());
// 获取和设置index位置上的元素,注意index必须介于[0, size)间
System.out.println(list.get(1));
list.set(1, "JavaWEB");
System.out.println(list.get(1));
// 在list的index位置插入指定元素,index及后续的元素统一往后搬移一个位置
list.add(1, "Java数据结构");
System.out.println(list);
// 删除指定元素,找到了就删除,该元素之后的元素统一往前搬移一个位置
list.remove("JVM");
System.out.println(list);
// 删除list中index位置上的元素,注意index不要超过list中有效元素个数,否则会抛出下标越界异常
list.remove(list.size()-1);
System.out.println(list);
// 检测list中是否包含指定元素,包含返回true,否则返回false
if(list.contains("测试课程")){
list.add("测试课程");
}
// 查找指定元素第一次出现的位置:indexOf从前往后找,lastIndexOf从后往前找
list.add("JavaSE");
System.out.println(list.indexOf("JavaSE"));
System.out.println(list.lastIndexOf("JavaSE"));
// 使用list中[0, 4)之间的元素构成一个新的SubList返回,但是和ArrayList共用一个elementData数组(修改SubList也会影响)
List<String> ret = list.subList(0, 4);
System.out.println(ret);
list.clear();
System.out.println(list.size());
}
2.3 遍历ArrayList
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// 使用下标+for遍历
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
// 借助foreach遍历
for (Integer integer : list) {
System.out.print(integer + " ");
}
System.out.println();
Iterator<Integer> it = list.listIterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();
}
2.4 ArrayList的扩容机制
ArrayList是一个动态类型的顺序表,即:在插入元素的过程中会自动扩容。以下是ArrayList源码中扩容方式:
Object[] elementData; // 存放元素的空间
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; // 默认空间
private static final int DEFAULT_CAPACITY = 10; // 默认容量大小
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// 获取旧空间大小
int oldCapacity = elementData.length;
// 预计按照1.5倍方式扩容
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果用户需要扩容大小 超过 原空间1.5倍,按照用户所需大小扩容
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果需要扩容大小超过MAX_ARRAY_SIZE,重新计算容量大小
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 调用copyOf扩容
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
// 如果minCapacity小于0,抛出OutOfMemoryError异常
if (minCapacity < 0)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
【总结】
-
检测是否真正需要扩容,如果是调用grow准备扩容
-
预估需要库容的大小
- 初步预估按照1.5倍大小扩容
- 如果用户所需大小超过预估1.5倍大小,则按照用户所需大小扩容
- 真正扩容之前检测是否能扩容成功,防止太大导致扩容失败
- 使用copyOf进行扩容
3. ArrayList的具体使用
3.1 简单的洗牌算法
public class Card {
public int rank;
public String suit;
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public String toString() {
return String.format("[%s %d]", suit, rank);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Cards {
public static final String[] suits = {"♠", "♥", "♣", "♦"};
public List<Card> buyCard() {
List<Card> cardList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= 13; j++) {
int rank = j;
String suit = suits[i];
Card card = new Card(rank, suit);
cardList.add(card);
}
}
return cardList;
}
public void shuffle(List<Card> cardList) {
Random random = new Random(20240623);
for (int i = cardList.size()-1; i >0; i--) {
int randIndex = random.nextInt(i);
swap(cardList, i, randIndex);
}
}
private void swap(List<Card> cardList, int i, int j) {
Card tmp = cardList.get(i);
cardList.set(i, cardList.get(j));
cardList.set(j, tmp);
}
}
import java.util.ArrayList;
import java.util.List;
public class TestCard {
public static void main(String[] args) {
Cards cards = new Cards();
List<Card> cardList = cards.buyCard();
System.out.println("刚买回来的牌:");
System.out.println(cardList);
cards.shuffle(cardList);
System.out.println("洗过的牌:");
System.out.println(cardList);
// 三个人,每个人轮流抓 5 张牌
List<List<Card>> hands = new ArrayList<>();
hands.add(new ArrayList<>());
hands.add(new ArrayList<>());
hands.add(new ArrayList<>());
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
hands.get(j).add(cardList.remove(0));
}
}
System.out.println("剩余的牌:");
System.out.println(cardList);
System.out.println("A 手中的牌:");
System.out.println(hands.get(0));
System.out.println("B 手中的牌:");
System.out.println(hands.get(1));
System.out.println("C 手中的牌:");
System.out.println(hands.get(2));
}
}
运行结果
刚买回来的牌:
[[♠ 1], [♠ 2], [♠ 3], [♠ 4], [♠ 5], [♠ 6], [♠ 7], [♠ 8], [♠ 9], [♠ 10],
[♠ 11], [♠ 12], [♠ 13], [♥ 1], [♥ 2], [♥ 3], [♥ 4], [♥ 5], [♥ 6], [♥ 7],
[♥ 8], [♥ 9], [♥ 10], [♥ 11], [♥ 12], [♥ 13], [♣ 1], [♣ 2], [♣ 3], [♣ 4],
[♣ 5], [♣ 6], [♣ 7], [♣ 8], [♣ 9], [♣ 10], [♣ 11], [♣ 12], [♣ 13], [♦ 1],
[♦ 2], [♦ 3], [♦ 4], [♦ 5], [♦ 6], [♦ 7], [♦ 8], [♦ 9], [♦ 10], [♦ 11], [♦ 12], [♦ 13]]
洗过的牌:
[[♦ 9], [♠ 5], [♠ 6], [♣ 10], [♣ 1], [♠ 11], [♦ 2], [♣ 8], [♥ 11], [♣ 3],
[♠ 4], [♦ 7], [♥ 5], [♣ 11], [♣ 5], [♦ 11], [♥ 1], [♥ 13], [♦ 12], [♣ 4],
[♦ 5], [♠ 8], [♠ 1], [♦ 4], [♦ 3], [♥ 10], [♦ 10], [♦ 13], [♠ 2], [♠ 7],
[♦ 1], [♣ 9], [♥ 2], [♦ 6], [♥ 6], [♠ 10], [♣ 2], [♣ 7], [♥ 7], [♥ 9],
[♥ 12], [♠ 9], [♥ 8], [♠ 3], [♣ 6], [♦ 8], [♣ 13], [♥ 4], [♣ 12], [♠ 12], [♠ 13], [♥ 3]]
剩余的牌:
[[♦ 11], [♥ 1], [♥ 13], [♦ 12], [♣ 4], [♦ 5], [♠ 8], [♠ 1], [♦ 4], [♦ 3],
[♥ 10], [♦ 10], [♦ 13], [♠ 2], [♠ 7], [♦ 1], [♣ 9], [♥ 2], [♦ 6], [♥ 6],
[♠ 10], [♣ 2], [♣ 7], [♥ 7], [♥ 9], [♥ 12], [♠ 9], [♥ 8], [♠ 3], [♣ 6],
[♦ 8], [♣ 13], [♥ 4], [♣ 12], [♠ 12], [♠ 13], [♥ 3]]
A 手中的牌:
[[♦ 9], [♣ 10], [♦ 2], [♣ 3], [♥ 5]]
B 手中的牌:
[[♠ 5], [♣ 1], [♣ 8], [♠ 4], [♣ 11]]
C 手中的牌:
[[♠ 6], [♠ 11], [♥ 11], [♦ 7], [♣ 5]]
3.2 杨辉三角
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> list = new ArrayList<>();
list.add(1);
ret.add(list);
for (int i = 1; i < numRows; i++) {
List<Integer> curRow = new ArrayList<>();
curRow.add(1);
for (int j = 1; j < i; j++) {
List<Integer> preRow = ret.get(i-1);
int x1 = preRow.get(j);
int x2 = preRow.get(j-1);
curRow.add(x1 + x2);
}
curRow.add(1);
ret.add(curRow);
}
return ret;
}
}
4. ArrayList的问题及思考
- ArrayList底层使用连续的空间,任意位置插入或删除元素时,需要将该位置后序元素整体往前或者往后搬
移,故时间复杂度为O(N) - 增容需要申请新空间,拷贝数据,释放旧空间。会有不小的消耗。
- 增容一般是呈2倍的增长,势必会有一定的空间浪费。例如当前容量为100,满了以后增容到200,我们再继
续插入了5个数据,后面没有数据插入了,那么就浪费了95个数据空间。