文章目录
总体框架图:
一、Collection接口
基本功能
遍历
方式一:集合转数组
方式二:使用集合自带的迭代器
- iterator 集合的专有遍历方式,通过集合的
iterator()
方法获得,所以迭代器是依赖于集合而存在的
//得到迭代器来遍历数组。迭代器与数组是相辅相成的
Iterator it =c.iterator();//通过集合的方法返回迭代器对象
while (it.hasNext()){
String s= (String) it.next();
System.out.println(s);
}
注意基础迭代器会存在并发修改异常的问题,这个后面再详细分析源码讨论
1. List
List 集合概述
- 有序集合(也称序列),用户可以精确控制列表中的每个元素的插入位置,通过整数索引访问元素
- 与 Set集合不同,List允许有重复元素
特点 - 有序:存储与取出的元素顺序一致
- 可重复:存储的元素可重复
List集合的特有方法
遍历(没有学泛型之前,都要强转)
-
Iterator 普通迭代器在一边迭代同时又出现修改集合操作的时候,会发生
异常
-
ListIterator listIterator()(继承Iterator,可以从后往前遍历,但开发中不怎么用它)遍历List集合时修改元素不会发生并发修改异常
出现的原因
普通迭代器在迭代期间不允许修改元素
迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际修改值不一致,则会出现:ConcurrentModificationException
解决的方案
用 普通 for循环
遍历,然后用集合对象做对应的操作即可,切记不可以用 增强 for 循环
或者使用专有迭代器ListIterator
列表迭代器【应用】
ListIterator 介绍
- 通过 List集合的
listIterator()方法
得到,所以说它是List集合特有的迭代器 - 用于允许程序员沿任一方向遍历的列表迭代器,从后往前遍历也可以实现
- 允许在迭代期间修改列表,并获取列表中迭代器的当前位置
增强for循环【应用】
for(String s : list) {
System.out.println(s);
}
//内部原理是一个Iterator迭代器
for(String s : list) {
if(s.equals("world")) {
list.add("javaee"); //ConcurrentModificationException
//和普通迭代器一样会抛出并发修改异常
}
}
List集合子类的特点【记忆】
- ArrayList::底层是数组结构实现,查询快、增删慢
- LinkedList: 底层是链表结构实现,查询慢、增删快
- Vector:底层数据结构是数组。线程安全
ArrayList
参考:https://blog.csdn.net/weixin_40304387/article/details/80790177
https://www.cnblogs.com/V1haoge/p/10414458.html
1. 概述
ArrayList底层使用的是数组。是List的可变数组实现,这里的可变是针对List而言,而不是底层数组。
数组有自身的特点,不变性,一旦数组被初始化,那么其长度就固定了,不可被改变。这就导致了ArrayList中的一个重要特性:扩容
。
public static void main(String[] args) {
ArrayList<String> arr=new ArrayList<>();
arr.add("hello");
arr.add("world");
arr.add("java");
//arr.add(3,"zy");
arr.add(4,"zy");//IndexOutOfBoundsException: Index: 4, Size: 3
System.out.println(arr);
}
案例:元素去重
/**
* 字符串去重:与自身比较
*/
public class ArrayListDemo01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("hello");
arrayList.add("java");
arrayList.add("hello");
arrayList.add("world");
for (int i = 0; i < arrayList.size() - 1; i++){
for (int j = i + 1; j<arrayList.size();j++){
if (arrayList.get(i).equals(arrayList.get(j))){
arrayList.remove(j);
j--;
}
}
}
//遍历集合
for (int i = 0; i < arrayList.size(); i++){
System.out.println(arrayList.get(i));
}
}
}
/**
* 自定义对象的集合,去重
* 自定义对象一定要重写 equals方法
*/
public class ArrayListDemo02 {
public static void main(String[] args) {
Student stu1 = new Student("张三",18);
Student stu2 = new Student("李四",20);
Student stu3 = new Student("张三",18);
Student stu4 = new Student("张三",18);
Student stu5 = new Student("张三",18);
ArrayList list = new ArrayList();
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
list.add(stu5);
ArrayList newList = new ArrayList();
// 元素去重
for (int i = 0; i < list.size(); i++ ){
Student s = (Student) list.get(i);//没有使用泛型,这里需要强转一下
if