对象的容器,实现了对对象的操作,类似数组功能
二、集合和数组的区别1.数组长度固定,集合长度不固定
2.数组可以存储基本类型和引用类型,集合只能存储引用类型
三、Collection接口迭代器:专门用来遍历集合的一种方式
hasNext(); 有下一个元素吗?如果有则返回true,否则false
next(); 获取下一个元素
remove(); 删除元素
public class Text {
public static void main(String[] args) {
//创建集合
Collection collection=new ArrayList();
//1.添加元素
collection.add("苹果");
collection.add("香蕉");
collection.add("西瓜");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
System.out.println("---------------------------");
//2.删除元素
collection.remove("西瓜");
collection.clear();
System.out.println("删除之后"+collection.size());
System.out.println("----------------------------");
//3.遍历元素(重点)
//3.1使用增强for
for(Object object:collection){
System.out.println(object);
}
//3.2使用迭代器(迭代器用来遍历集合的一种方式)
//hasNext();有没有下一个元素。next();获取下一个元素。remove();删除当前元素
Iterator it= collection.iterator();
while(it.hasNext()){
String s=(String)it.next();
System.out.println(s);
//不能使用collection删除
//collection.remove(s);
it.remove();
}
System.out.println("元素个数:"+collection.size());
System.out.println("-----------------------------");
//4.判断
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());
}
}
特点:有序,有下标,可以重复
//List子接口的使用
public class Demo01 {
public static void main(String[] args) {
//先创建集合对象
List list = new ArrayList<>();
//1.添加元素
list.add("苹果");
list.add("小米");
list.add(0, "华为");
System.out.println("元素个数:" + list.size());
System.out.println(list.toString());
System.out.println("-------------------------");
//2.删除元素
//3.遍历
//3.1使用for遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("---------------------------");
//3.2使用增强for
for (Object object : list) {
System.out.println(object);
}
System.out.println("-----------------------------");
//3.3使用迭代器
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
System.out.println("--------------------------");
}
//3.4列表迭代器
ListIterator lit=list.listIterator();
while(lit.hasNext()) {
System.out.println(lit.nextIndex() + ":" + lit.next());
}
}
}
ArrayList
源码分析:DEEAULT_CAPACITY=10; 默认容量
注意:如果没有向集合中添加任何元素时,容量为0
elementDate 存放元素的数组
size 实际元素个数
add() 添加元素
linkedList
存储结构:双向链表
泛型泛型类,泛型接口,泛型方法
好处:提高代码的重用性,防止类型转换异常,提高代码的安全性
Set实现类
HashSet:基于Hashcode实现元素不重复
当存入元素哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入
Hashset集合的使用:
存储结构:哈希表(数组+链表+红黑树)
存储过程:(1)根据hashset计算保存的位置,如果此位置为空,则直接保存,如果不为空,执行第二步。 (2)再执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表。
TreeSet:1.基于排列顺序实现元素不重复
- 实现了SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排列规则
- 通过compareTo()方法确定是否为重复元素
Comparator:比较器,compareTo()方法返回值为0,认为是重复元素
Map集合
Map接口的特点:(1)存储一对数据(2)无序,无下标(3)键不可重复,值可重复
HashMap集合的使用:
存储结构:哈希表
put方法:
public V put(k key, V value){
Return putVal(hash(key),key,value,false,true);
}
Collections工具类



