Collection<>接口
No Country for Old Men
Collection的子类的构造器里能接受另外的Collection子类,并用它来将自身初始化。
例:
ArrayLIst list = new ArrayList();
Conllection conllection = new ArrayList(list.asList);
Collection.addAll()将指定 collection 中的所有元素都添加到此 collection 中。
Collection.addAll()方法要比调用Collection子类的构造方法来的快。
Collection.addAll()只能接受另一个Collection对象作为参数,因此不如Arrays.asList()或Collections.addAll()灵活。
调用Collections.addAll()十分方便,因此是首选方式。
Collection是描述所有序列容器共性的根接口,它表达了其他若干接口的共性。因此我们可以通过使用Collection来创建更通用的代码(接口的作用)。
如此一来我们的代码就可应用于更多的对象类型(如果我们写了一个接受Collection类型的方法,那么此方法自然可以接受实现了Collection接口的子类啦。)不过由于Collection是Iterable的子接口,所以自然可以使用迭代器来使用一些Collection类型的共性方法。
自然我们如果要实现一个Collection类型也需要实现iterator()方法(Iterable接口规定了你必须要实现它)了。所以我们有了两种方法来使用Collection类型的共性方法。
例:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest {
public static void main(String[] args){
Collection<String> collection = new ArrayList<String>();
for (String s : "No Country of Old Men".split(" ")) {
((ArrayList<String>) collection).add(s);
}
Iterator<String> it = collection.iterator();
display(it);
display(collection);
}
public static void display(Collection<String> collection){
for (String s : collection) System.out.print(s+" ");
//Collection接口是Iterable接口的子接口,所以可以使用foreach语句
System.out.println();
}
public static void display(Iterator<String> it){
while (it.hasNext()) System.out.print(it.next()+" ");
System.out.println();
}
}
//No Country for Old Men
//No Country for Old Men
Foreach与迭代器
foreach语法主要用于数组的,但是也可用于任何Collection类型对象。
之所以能够工作,是因为Java SE5引入了新的被称为Iteranble的接口,该接口包含一个能够产生Iterator的iterator()方法,并且Iterable接口被foreach用来在序列中移动,因此如果你创建了任何实现Iterable的类,那么它都可以用于foreach语句中。 ——《Java编程思想》
因此实现Iterator接口可使你自己的类能够用于foreach语句或使用迭代器。
例:
import java.util.Iterator;
public class IterableTest implements Iterable<String>{
private String[] str = "No Counter for Old Men".split(" ");
private int index = 0;
@Override
public Iterator iterator() {
return new Iterator() {
@Override
public boolean hasNext() {
return index<str.length;
}
@Override
public String next() {
return str[index++];
}
};
}
public static void main(String[] args){
for (String s : new IterableTest()) {
System.out.print(s+" ");
}
System.out.println();
Iterator it = new IterableTest().iterator();
while (it.hasNext()){
System.out.print(it.next()+" ");
}
}
}
//No Country for Old Men
//No Country for Old Men