一、集合Collection
1、为什么出现集合类?
面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。
2、数组和集合类同是容器,有何不同?
数组虽然也可以存储对象,但长度是固定的;集合长度是可变的。数组中可以存储基本数据类型,集合只能存储对象。
3、集合类的特点
集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。
4、Collection接口概述
Collection 层次结构中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。
5.Cllection接口中的成员方法:
* boolean add(E e):添加一个集合元素
* boolean remove(Object o):删除一个集合元素
* void clear():清除集合中所有的元素
* boolean contains(Object o):判断集合中是否包括此元素
* boolean isEmpty(): 如果此 collection 不包含元素(此集合为null),则返回 true。
* int size():集合的长度
* boolean addAll(Collection c):添加所有元素
* boolean removeAll(Collection c):删除集合中所有元素
* boolean containsAll(Collection c):判断集合A中是否包含集合B中的元素
* boolean retainAll(Collection c):移除此 collection 中未包含在指定 collection 中的所有元素。
代码解读:
public class CollectionDemo {
public static void main(String[] args) {
// Cannot instantiate the type Collection:无法实例化类型集合
// Collection c = new Collection();由于Collection是接口,所以无法被实例化
// 创建一个集合A
Collection c = new ArrayList();// 多态,父类引用指向子类对象
// 添加一个元素
c.add("hello");
c.add("world");
c.add("java");
// 删除一个集合元素
// c.remove("hello");
// 清除集合中所有的元素
// c.clear();
// 判断集合中是否包括此元素
/*
* boolean ct = c.contains("java1"); if (ct == true) {
* System.out.println("有此元素"); } else { System.out.println("没有此元素"); }
*/
// 判断该集合是否为空集合,如果为空集合(null)返回true,不为空返回false
/*
* boolean cd = c.isEmpty(); System.out.println(cd);
*/
// 创建一个集合B
Collection c2 = new ArrayList();
c2.add("hello");
c2.add("cuntry");
c2.add("javaEE");
// System.out.println(c2);
// boolean addAll(Collection c):添加所有元素
// c2.addAll(c);
// System.out.println(c2);
// System.out.println(c);
// boolean containsAll(Collection c):判断集合A中是否包含集合B中的元素
// boolean bc2 = c2.containsAll(c);//这个判断是判断集合B中是否包含集合A中的所有元素,包含为true
// System.out.println(bc2);//true
// boolean retainAll(Collection c)
// 移除此 collection 中未包含在指定 collection 中的所有元素。
boolean b = c2.retainAll(c);// 输出集合A与集合B的交集
/*
* 注意事项: 集合B.retainAll(集合B)
* 如果集合A有元素,集合B也有元素,交集有:null,相同添加的元素
* 如果集合A有元素,集合B没有元素,那么false
* 如果集合A没有元素,集合B有元素,那么为true
*/
System.out.println(b);
System.out.println(c2);
System.out.println(c);
}
}