1. Collection接口的概述
是用来存放对象的数据结构。其中长度可变,而且集合中可以存放不同类型的对象。并提供了一组操作成批对象的方法。
数组的缺点:长度是固定不可变的,访问方式单一,插入、删除等操作繁琐。
2. 集合的继承结构
Collection接口
-- List接口 : 数据有序,可以重复。
-- ArrayList子类
-- LinkedList子类
-- Set接口 : 数据无序,不可以存重复值
-- HashSet子类
-- Map接口 : 键值对存数据
-- HashMap
Collections工具类
3. 常用方法
boolean add(E e):添加元素。
boolean addAll(Collection c):把小集合添加到大集合中 。
boolean contains(Object o) : 如果此 collection 包含指定的元素,则返回 true。
boolean isEmpty() :如果此 collection 没有元素,则返回 true。
Iterator<E> iterator():返回在此 collection 的元素上进行迭代的迭代器。
boolean remove(Object o) :从此 collection 中移除指定元素的单个实例。
int size() :返回此 collection 中的元素数。
Objec[] toArray():返回对象数组
4. 案例测试常用方法
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestCollection {
public static void main(String[] args) {
Collection c = new ArrayList();//接口无法直接创建对象
c.add("hello");//添加元素
c.add("java");//添加元素
c.add("~");//添加元素
c.add(10);//jdk5后有自动装箱功能,相当于把10包装Integer.valueOf(10)
System.out.println(c.remove("~"));//移除元素
System.out.println(c.contains("a"));//判断包含关系
System.out.println(c.size());//集合的长度
System.out.println(c);
//for遍历集合
for(int i =0 ;i<c.size();i++) {
System.out.println(c.toArray()[i]);
}
//iterator迭代器遍历
Iterator it = c.iterator();//对 collection 进行迭代的迭代器
while (it.hasNext()) {//如果仍有元素,则返回 true
System.out.println(it.next());//返回迭代获取到的下一个元素
}
}
}