集合概述
集合存储的都是对象!
集合框架
学习目标
学习方法
Collection集合
所有单列集合最顶层的接口,里面定义了所有单列集合共性的方法
任意的单列集合都可以使用Collection接口中的方法
共性的方法:
public boolean add(E e); //把给定的对象添加到当前集合
public void clear(); //清空集合中的所有元素
public boolean remove(E e); //把给定的元素在集合中删除
public boolean contains(E e); //判断当前集合中是否包含给定的对象
public boolean isEmpty(); //判断当前集合是否为空
public int size(); //返回集合中元素的个数
public Obiect[] toArray(); //把集合中的元素存储到数组中
下面以ArrayList集合为例子,进行操作
public class Demo01Collection {
public static void main(String[] args) {
//创建一个集合对象,可以使用多态
Collection<String> coll = new ArrayList<>();
System.out.println(coll);
//public boolean add(E e); //把给定的对象添加到当前集合
boolean b1 = coll.add("老八");
System.out.println("b1:"+b1);
System.out.println(coll);
coll.add("giao");
coll.add("mabaoguo");
System.out.println(coll);
System.out.println("=====================");
//public boolean remove(E e); //把给定的元素在集合中删除
boolean b2 = coll.remove("giao");
System.out.println(b2);
System.out.println(coll);
b2 = coll.remove("123");
System.out.println(b2);
System.out.println("=====================");
//public boolean contains(E e); //判断当前集合中是否包含给定的对象
boolean b3 = coll.contains("老八");
System.out.println(b3);
b3 = coll.contains("123");
System.out.println(b3);
System.out.println("=====================");
//public boolean isEmpty(); //判断当前集合是否为空
boolean b4 = coll.isEmpty();
System.out.println(b4);
System.out.println("=====================");
//public int size(); //返回集合中元素的个数
Integer a = coll.size();
System.out.println(a);
System.out.println("=====================");
//public Obiect[] toArray(); //把集合中的元素存储到数组中
Object[] arr = coll.toArray();
for (int i = 0; i < coll.size(); i++) {
System.out.println(arr[i]);
}
System.out.println("=====================");
//public void clear(); //清空集合中的所有元素
coll.clear();
System.out.println(coll);
System.out.println("=====================");
}
}