java collections framework - yaokun123/php-wiki GitHub Wiki

集合框架

一、集合框架概述

为什么出现集合类?

面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。

数组和集合类同时容器,有何不同

数组虽然也可以存储对象,但长度是固定的,集合长度是可变的。

数组中可以存储基本数据类型,集合中只能存储对象

集合类的特点

集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。

二、集合框架-体系&共性功能

集合容器因为内部数据结构不同,有多种具体容器。不断向上抽取,就形成了集合框架。

框架的顶层Collection接口:

Collection的常见方法

  • 1、添加
boolean add(Object obj);
boolean addAll(Collection coll);
  • 2、删除
boolean remove(Object obj);
boolean removeAll(Collection coll);
void clear();
  • 3、判断
boolean contains(Object obj);
boolean containsAll(Collection coll);
boolean isEmpty();
  • 4、获取
int size();
Iterator iterator();//取出元素的方式,迭代器

5、其他

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);

        
    }
}

三、集合框架-List和Set的区别

List:有序的collection(也称为序列,存入和取出的顺序一致)。元素都有索引(角标),元素可以重复。

Set:元素不能重复,无序。

  • 1、List(子类:Vector(内部是数组数据结构,是同步的,增删查询都慢)/ArrayList(内部是数组数据结构,是不同步的。替代了Vector,查询的速度快)/LinkedList(内部是链表数据结构,是不同步的,增删元素的速度快))
1、添加:
void add(index,element);
void add(index,collection)

2、删除
Object remove(index);

3、修改
Object set(index,element);

4、获取
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集合具备该迭代功能

  • 2、set(子类:HashSet(内部数据结构是哈希表,是不同步的)/LinkHashSet()/TreeSet(可以对set集合中的元素进行排序,是不同步的))