今天学习的内容是集合类之Collection接口
学习数组时说过:“应该优选集合而不是数组”,这是因为集合的长度是可变的,并且通过使用泛型解决了类型安全问题,使用自动打包机制解除了存储基本数据类型的限制,在实际开发中更加灵活。
那什么是集合呢?就像数组一样,集合就是用来存放对象的容器,Java提供了一套相当完整的集合类API供程序员使用。集合类根据其内部数据结构的不同分为多种,比如最常见的List集合,Set集合与Map集合,它们分别实现了List接口,Set接口与Map接口。其中List接口与Set接口继承了Collection接口,因此Collection接口是集合框架(Collection Framework)的根接口。注意Map接口虽然没有继承Collection接口,但也应该被当作是集合框架的一份子。
Collection接口中定义了许多List集合与Set集合通用的方法:
- add(E e) 将指定对象添加到此集合中
- addAll(Collection<? extends E> c) 将指定集合中的所有元素添加到此集合中
- remove(Object o) 将指定对象从此集合中删除
- removeAll(Collection<?> c) 删除此集合中也包含在指定集合中的所有元素
- clear() 删除此集合中所有元素
- contains(Object o) 判断此集合中是否含有指定元素
- containsAll(Collection<?> c) 判断此集合中是否包含指定集合的所有元素
- size() 返回此集合中元素的个数
- isEmpty() 判断此集合是否为空
- iterator() 返回在此集合的元素上进行迭代的迭代器对象,用于遍历获取集合中的元素
- retainAll(Collection<?> c) 保留两个集合的交集元素
使用上述方法的示例程序(以ArrayList为例):
public class Test51 {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<String>();
show_1(coll);
Collection<Integer> coll_1 = new ArrayList<Integer>();
Collection<Integer> coll_2 = new ArrayList<Integer>();
Collection<Integer> coll_3 = new ArrayList<Integer>();
show_2(coll_1, coll_2, coll_3);
show_Iterator(coll);
}
public static void show_Iterator(Collection<String> coll) {
// 迭代器演示
coll.add("a");
coll.add("b");
coll.add("c");
coll.add("d");
coll.add("e");
coll.add("f");
Iterator<String> it = coll.iterator();//Collection接口具有iterator()方法
//iterator()方法返回的是集合类中的内部类对象
//这个内部类实现了Iterator接口,每个集合类的具体实现方法都不同
while (it.hasNext()) {
System.out.println(it.next());//next()方法返回的是泛型的规定的类型
}
}
public static void show_2(Collection<Integer> coll_1, Collection<Integer> coll_2, Collection<Integer> coll_3) {
// 添加元素
coll_1.add(1);// 由于自动打包机制的出现,集合类也可以存放基本数据类型
coll_1.add(2);
coll_1.add(3);
coll_2.add(3);
coll_2.add(4);
coll_3.addAll(coll_1);
coll_3.addAll(coll_2);
System.out.println("集合:" + coll_3 + " 集合长度:" + coll_3.size());// 集合:[1, 2, 3, 3, 4] 集合长度:5
// 判断
System.out.println(coll_3.containsAll(coll_1));// true
System.out.println(coll_3.containsAll(coll_2));// true
// 保留部分元素
coll_3.retainAll(coll_1);// 将此集合中与指定元素的相同元素全部保留
System.out.println("集合:" + coll_3 + " 集合长度:" + coll_3.size());// [1, 2, 3, 3] 集合长度:4
// 删除元素
coll_3.removeAll(coll_1);// 将此集合中与指定元素的相同元素全部删除
System.out.println("集合:" + coll_3 + " 集合长度:" + coll_3.size());// 集合:[] 集合长度:0
}
public static void show_1(Collection<String> coll) {
// 添加元素
coll.add("abc");
coll.add("de");
coll.add("f");
System.out.println("集合:" + coll + " 集合长度:" + coll.size());// 集合:[abc, de, f] 集合长度:3
// 判断
System.out.println(coll.contains("abc"));// true
System.out.println(coll.isEmpty());// false
// 删除元素
coll.remove("abc");
System.out.println("集合:" + coll + " 集合长度:" + coll.size());// 集合:[de, f] 集合长度:2
coll.clear();
System.out.println("集合:" + coll + " 集合长度:" + coll.size());// 集合:[] 集合长度:0
}
}