特点:代表一组任意类型的对象,无序、无下标、不能重复。

方法:

1.boolean add(Object obj)添加一个对象

2.boolean addAll(Collection c)将一个集合中的所有对象添加到此集合中。

3.void clear()清空此集合中的所有对象。

4.boolean contains 检查此集合中是否包含o对象

5.boolean equals(Object obj)比较此集合是否与指定对象相等

6.boolean isEmpty 判断此集合是否为空

7.boolean remove(Object o)在此集合中移除o对象

8.int size 返回此集合中的元素个数

9.Object [] toArray 将此集合转换为数组

public class Demo01 {
public static void main(String[] args) {
//添加元素
Collection collection=new ArrayList();
collection.add("苹果");
collection.add("香蕉");
collection.add("西瓜");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//删除元素
collection.remove("苹果");
//collection.clear();//清空
System.out.println("删除之后:"+collection.size());

    //遍历元素[重点]
    //方法1:增强for(for each)
    System.out.println("===========方法1===========");
    for (Object object:collection) {
        System.out.println(object);
    }
    //方法2:使用迭代器(迭代器是专门用来遍历集合的一种方式)
    //Iterator的三个方法
    //1.hasNext();有没有下一个元素
    //2.next();获取下一个元素
    //3.remove();删除当前元素
    System.out.println("=============方法2for增强============");
    Iterator it=collection.iterator();
    while (it.hasNext()){
       String s=(String) it.next();//强制转换
        System.out.println(s);
        //注意:迭代器在迭代过程中不允许用collection的remove方法,否则会报错;例如:collection.remove(s);
        //但是可以使用迭代器的remove方法删除
        //it.remove();

    }
    System.out.println("元素个数:"+collection.size());

    //4.判断
    System.out.println(collection.contains("西瓜"));//判断此集合中是否包含这个元素,有为true 无为flase
    System.out.println(collection.isEmpty());//判断此集合是否为空,空为true 非空为flase

}

}

public class Demo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection=new ArrayList();
Student S1= new Student("张三",18);
Student S2= new Student("李四",19);
Student S3= new Student("王五",20);
//1.添加数据
collection.add(S1);
collection.add(S2);
collection.add(S3);

    //2.删除数据
  collection.remove(S1);
  //collection.remove(new Student("王五",18));
    //collection.clear();
    //System.out.println("删除之后:"+collection.size());

    //3.遍历
    //1.增强for
    System.out.println("------------增强for方法------------");
    Iterator it=collection.iterator();
    for (Object object:collection) {
        Student s=(Student) object;
        System.out.println(s.toString());
    }
    //2.迭代器: hasNext() next() remove() ;迭代过程中不能使用collection的删除方法
    System.out.println("------------迭代器方法------------");
    Iterator iterator=collection.iterator();
    while (iterator.hasNext()){
        Student s=(Student) iterator.next();
        System.out.println(s.toString());
    }


    //4.判断
    System.out.println(collection.contains(S2));
    System.out.println(collection.isEmpty());






}

}