在编写JAVA程序中,我们经常会遇到需要保存一组数据对象,此时,我们可以采用对象数组来进行多个对象的保存,但对象数组存在一个最大的问题即在于长度上的限制,如果说我们现在要保存一组对象,但是我们并知道数组对象到底有多少个的时候,那么此时就遇到了困难,因此为了解决此问题,在JDK1.2中,提出了类集框架的概念,并在JDK1.5中对此框架进行了修改,加入了泛型的支持,从而保证了操作的安全性。而在整个集合中,提供了几个集合核心操作的接口,分别为:Collection、Set、List、Enumeration、Iterator、ListIterator等。
1)单值保存的最大父接口:Collection
所谓的单值保存指的是每次操作只保存一个对象,每次增加只增加一个对象,而在Collection接口之中定义了如下几个常用的方法:
package com.njupt.study.collection; import java.util.Iterator; public interface Collection<E> extends Iterable<E>{ /** * 增加数据 * @param e * @return */ boolean add(E e); /** * 删除指定的元素 * @param o * @return */ boolean remove(Object o); /** * 清除数据 */ void clear(); /** * 判断集合是否为空 * @return */ boolean isEmpty(); /** * 获取元素的个数 * @return */ int size(); /** * 查找一个数据是否存在 * @param o * @return */ boolean contains(Object o); /** * 将集合变为对象数组后返回 * @return */ Object[] toArray(); /** * 将集合变为指定类型的对象数组 * @param <T> * @param a * @return */ <T> T[] toArray(T[] a); /** * 为Iterator接口实例化,来源于父类接口Iterable */ Iterator<E> iterator(); }
Collection接口本身在开发之中并不会直接的去使用,而在开发之中往往会使用两个子接口:List、Set。
2)允许重复的子接口:List
List接口是Collection接口的子接口,是有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。
public interface List<E>extends Collection<E>
List接口对Collection接口进行了大量的扩充操作,而主要的扩充方法有如下几个:
public interface List<E> extends Collection<E> { /** * 返回指定位置上的数据 * @param index * @return */ E get(int index); /** * 修改指定位置上的数据 * @param index * @param element * @return */ E set(int index, E element); /** * 为ListIterator接口实例化 * @return */ ListIterator<E> listIterator(); }