集合概述

java中有很多集合类,它们都存在于java.util包中。

所有的集合类都实现基本的Collection接口,该接口的原型如下:
public interface Collection<E> {
	boolean add(E element);
	Iterator<E> iterator();
	...
}


其中,add和iterator是该接口的2个基本方法。

Iterator我们称之为迭代器,它也是一个java接口,具有3个基本方法,原型如下:
public interface Iterator<E> {
	E next();
	boolean hasNext();
	void remove();
}


遍历java集合的2种方法
1)使用迭代器
Collection<String> c = ...;
Iterator<String> iter = c.iterator();
while (iter.hasNext()) {
	String element = iter.next();
	//do something with element
}


2)使用for each循环(JDK5开始支持)
for (String element:c) {
	//do something with element
}


移除元素
移除元素必须先跳过该元素,然后再调用remove方法,代码如下:
Iterator<String> ir = c.iterator();
it.next();
it.remove();	//remove the 1st element


你可能感兴趣的:(java,C++,c,C#)