1.Collection
单列集合顶层接口,一次添加一个元素;
1.collection常用的方法
Collection接口中包含了list和set集合通用的方法;
Collection<Student>coll=new ArrayList<>();//接口多态的方式创建集合;
Student s1=new Student("陈炎炎",19);
Student s2=new Student("懒羊羊",24);
coll.add(s1);
coll.add(s2);
coll.remove(s1);
Student s3=new Student("懒羊羊",24);
System.out.println(coll.contains(s3));
值得注意的一点是remove和contains方法依赖于对象的equals方法,所以在定义自定义对象时要重写对象的equals方法;
2.集合的通用遍历方式
Collection<Student>coll=new ArrayList<>();//接口多态的方式创建集合;
Student s1=new Student("陈炎炎",19);
Student s2=new Student("懒羊羊",24);
coll.add(s1);
coll.add(s2);
A.迭代器遍历
Iterator<Student> it = coll.iterator();
while(it.hasNext()){
Student s = it.next();
System.out.println(s);
}
B.增强for遍历
for (Student student : coll) {
System.out.println(student);
}
C.lambda表达式遍历
D.普通for遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
适用于遍历有索引的集合和数组;
2.List
特点:存储有序,有索引,可以重复
1.list常用方法
由于list有索引,所以增加了list操作索引的Api
2.ArrayList
3.LinkedList
底层是基于双向链表实现-----增删快,查询慢的一种数据结构;
特有方法:
4.并发修改异常
3.Set
1.HashSet
1. 创建一个默认长度16,默认加载因为0.75的数组,数组名table
2 根据元素的哈希值跟数组的长度计算出应存入的位置 判断当前位置是否为null,如果是null直接存入,如果位置不为null,表示有元素, 则调用equals方法比较属性值,如果一样,则不存,如果不一样,则存入数组。
3. 当数组存满到16*0.75=12时,就自动扩容,每次扩容原先的两倍 。
4.当链表挂载元素超过了8个 (阈值) 检查数组长度 :没有到达64, 扩容数组, 到达了64, 会转换为红黑树
2.LinkedHashSet
增加了双向链表来保证数据存取有序;
2.TreeSet
底层为红黑树;
红黑树的添加规则:
TreeSet的两种排序方式:
1.自然排序
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
this :当前要添加的元素;
o: 已经在红黑树中存在的元素;
返回值大于0,存右边;
返回值小于0,存左边;
返回值等于0,该元素已经存在,不存
2.比较器排序
3.注意事项
4.Map
5.Collections(集合常用工具类)