接口Collection
1.集合概况
2.集合特点
1.能添加不同类型的元素
注意:集合中只能添加 引用数据类型(只能添加对象类型)
2.长度可变
集合collection接口中的方法
集合可以保存不同数据类型的数据
保存基本数据类型是以自动装箱的形式 进行存储
3.Collection的基本方法
public static void fun1() {
//创建一个集合 多态的声明方法
Collection collection = new ArrayList();
//添加方法
//ArrayList中的add 不可能返回失败
//不能返回失败 为什么还要设计返回值呢 -- 思想
//适用所有的子类 子接口
boolean b1 = collection.add('a');
boolean b2 =collection.add('b');
boolean b3 =collection.add('c');
//当你向集合中添加基本数据类型的时候
//系统会帮你 自动装箱 把基本数据类型变成它的包装类
boolean b4 =collection.add(10);
boolean b5 =collection.add(true);
//打印集合
System.out.println(collection);
System.out.println(b1);
//获取集合的长度
System.out.println(collection.size());
//判断是否包含某个元素
boolean b7 = collection.contains('b');
System.out.println(b7);
//从集合中删除一个元素
boolean b8 = collection.remove('b');
//操作的是 集合本身
System.out.println(collection);
//判断集合 是否为空
boolean b9 = collection.isEmpty();
System.out.println(b9);
//清空数组
collection.clear();
System.out.println(collection);
}
4.打印字符串
public static void fun2() {
Collection collection = new ArrayList();
//添加 a b c d
collection.add('a');
collection.add('b');
collection.add('c');
collection.add('d');
//遍历集合中的每一个元素
Object[] array = collection.toArray();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
5.//创建集合 保存3个学生 只打印姓名
public static void fun3() {
Collection collection = new ArrayList();
collection.add(new Student("鹏", 18));
collection.add(new Student("水", 17));
collection.add(new Student("茜", 16));
//集合转数组(相当于有一个 向上转型)
Object[] array = collection.toArray();
//Student[] array = (Student[])collection.toArray();错误的强转方法
//强转注意: 把数组中每一个对象进行强转
//遍历数组
for (int i = 0; i < array.length; i++) {
//array[i]直接从数组中取出来 是Object类型
//对象调方法 强转注意: 把数组中每一个对象进行强转
//要想使用 Student类中的方法 需要强转 向下转型
//必须是这个类型 你才能强转
Student student = (Student)array[i];
System.out.println(student.getName());
}
}
6.测试addAll removeAll 和 retainAll 方法
public static void fun4() {
Collection c1 = new ArrayList();
c1.add('a');
c1.add('b');
Collection c2 = new ArrayList();
c2.add('a');
c2.add('b');
c2.add('c');
c2.add('d');
//将c1中的元素添加到c2中
boolean b1 = c2.addAll(c1);
//将两个集合的重合元素 删除
//谁调用这个方法 就删除谁的元素 另一个集合不变
//只删除交集 重复也可以删
boolean b2 = c2.removeAll(c1);
//把两个集合的交集取出来 保存在c1(谁调的方法 保存在谁那)
//如果c1集合和c2集合 求出交集放到c1中 如果c1和原来对比 不发生变化返回false 发生变化返回true
boolean b3 = c2.retainAll(c1);
System.out.println(c1 + "---");
System.out.println(c2);
}
7.迭代器
使用迭代器遍历集合
Collection collection = new ArrayList();
//迭代时 相当于有一个指针 指向集合的首位置
//每调用一次 next 方法 这个指针就向下移一格
collection.add('a'); // ⬅️
collection.add('b'); //
collection.add('c'); //
collection.add('d'); //
//遍历集合
Iterator iterator = collection.iterator();
//如果有元素 就获取 没元素 就停止循环
while (iterator.hasNext()) {
//注意: 迭代时 循环 只能使用一次next()方法
System.out.println(iterator.next());