面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。
数组虽然也可以存储对象,但长度是固定的,集合长度是可变的。
数组中可以存储基本数据类型,集合中只能存储对象
集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。
集合容器因为内部数据结构不同,有多种具体容器。不断向上抽取,就形成了集合框架。
框架的顶层 Collection 接口:
boolean add(Object obj);
boolean addAll(Collection coll);
boolean remove(Object obj);
boolean removeAll(Collection coll);
void clear();
boolean contains(Object obj);
boolean containsAll(Collection coll);
boolean isEmpty();
int size();
Iterator iterator();//取出元素的方式,迭代器
boolean retainAll(Collection coll);//取交集
Object[] toArray();//将集合转换成数组
import java.util.Collection;
public class CollectionDemo{
public static void main(String[] args){
Collection coll = new ArrayList();
this.show();
}
public static void show(Collection coll){
//1、新加元素
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
System.out.println(coll);
//2、删除元素
coll.remove("abc2");
System.out.println(coll);
}
}
(子类:Vector(内部是数组数据结构,是同步的,增删查询都慢)/ArrayList(内部是数组数据结构,是不同步的。替代了Vector,查询的速度快)/LinkedList(内部是链表数据结构,是不同步的,增删元素的速度快))
void add(index,element);
void add(index,collection)
Object remove(index);
Object set(index,element);
Object get(index);
int indexOf(object);
int lastIndexOf(object);
List subList(from,to);
Iterator it = list.iterator();
ListIterator it = list.listIterator()
注意:在迭代器过程中,不要使用集合操作元素,容易出现异常。
可以使用 Iterator 接口的子接口 ListIterator,拿到列表迭代器,来完成再迭代中对元素进行更多操作。(通过list的listIterator()方法)
注意:只有list集合具备该迭代功能
(子类:HashSet(内部数据结构是哈希表,是不同步的)/LinkHashSet()/TreeSet(可以对set集合中的元素进行排序,是不同步的))

