集合概述 以及 Collection接口

集合框架:接口 实现 算法

接口

  核心集合接口 (core collection interface) 是Java集合框架的基础,如下图所示:

  

  • 声明实例时 应该指定所包含的对象的类型 这样编译器在编译的时候会验证你放到这个集合的对象类型是否正确 减少运行时期的错误。
  • Collection接口是所有接口实现的基础,在需要最大程度的通用性时可以使用它传递和操作集合(转换构造器)
  • List可以包含重复元素 精确控制插入位置 以及 通过索引访问元素。
  • 每个Queue实现都必须指定其排序属性。
  • SortedSet按照升序维护其元素的Set。
  • SortedMap按键升序维护其映射的Map。

Collection : size isEmpty contains add(return true) remove(return true) iterator

1. 遍历集合

for-each结构

for(Object o : collection) {

  System.out.println(o);

    // for-each结构隐藏迭代器,不能调用remove。

}

迭代器 (允许删除元素)

public interface Iterator<E> {

  boolean hasNext();

  E next();

  void remove();

    // 使用Iterator.remove是修改集合的唯一安全途径,对于next方法的每次调用,只能调用一次remove方法,否则会抛出一个异常。

}

// 遍历集合的同时删除特定元素
public static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext();) {
        if (!(it.next() == null)) {
            it.remove();
        }
    }
}

2. 批量操作

containsAll addAll removeAll retainAll(交集) clear removeAll(Collections.singleton(e))

3. Collection接口的数组操作

Object[] aarray = alist.toArray();
String[] barray = alist.toArray(new String[0]);

原文地址:https://www.cnblogs.com/Knuth/p/3101688.html