集合 (collection) 的概念在 Collection 接口中得到抽象, 接口位于 java.util 包中
Collection 接口定义:
- public interface Collection<AnyType> extends Iterable<AnyType>
- {
- int size();
- boolean isEmpty();
- void clear();
- boolean contains(AnyType x);
- boolean add(AnyType x);
- boolean remove(AnyType x);
- java.util.Iterator<AnyType> iterator();
- }
扩展了 Iterable 接口可以使用 for-each 循环(增强 for 循环)
- for(AnyType item:arry)
- System.out.print(item);
实现 Iterable 接口的集合必须提供一个 iterator 的方法, 该方法返回一个 Iterator 类型的对象. Iterator 在 java.util 包中
- public interface Iterator<AnyType>{
- boolean hasNext();// 集合中是否存在下一项
- AnyType next();// 给出迭代器中当前项的下一项
- void remove();// 删除由 next 最新返回的项(必须要调用一次 next)
- }
所以可以改写 for-each 循环
- Iterator<AnyType> itr=arry.iterator();
- while(arry.hasNext()){
- AnyType item=arry.next();
- System.out.print(item);
- }
直接使用 Iterator 时, 如果正在被迭代的集合进行结构上的改变, 那么迭代器就不再合法. 但是迭代器调用自己的 remove 方法, 那么迭代器却时合法的.
表: 由 java.util 包中的 List 接口指定. List 接口继承了 Collection 接口.
- public interface List<AnyType> extends Collection<AnyType>{
- AnyType get(int idx);
- AnyType set(int ids,AnyType newVal);
- void add(int ids,AnyType x);
- void remove(int idx);
- ListIterator<AnyType> listIterator(int pos);
- }
List ADT 提供了两种实现方式: ArrayList 类提供了一种可增长数组的实现, LinkedList 类提供了一种双链表实现
for-each 循环在编译器中默认使用迭代器, 所以使用 for-each 循环不能对被循环者进行结构改变
- public interface ListIterator<AnyType> extends Iterator<AnyType>
- {
- boolean hasPrevious();// 从后开始: 集合中向前是否还有元素
- AnyType previous();// 从后开始: 迭代器中的当前元素的前一项
- void add(AnyType x);// 从 next 和 previous 中决定插入的当前项; 列入:>5 8 14 6 9(正常起点: next 返回 5,previous 非法, add 把项放在 5 之前) 5> 8 14 6 9() 5 8 14 6 9>;add 把项放在 next 之前 previous 之后
- void set(AnyType newVal);// 改变迭代器看到的最后一个值
- }
来源: http://www.bubuko.com/infodetail-2554033.html