1 集合与迭代器
如果所编写的方法接受一个
Collection
,那么该方法可以应用于任何实现了Collection
的类——这也就使得一个新类可以选择去实现Collection
接口,以便该方法可以使用它。
集合之间的所有共性都是通过迭代器实现的。
package com.hcong.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* @Classname InterfaceVsIterator
* @Date 2023/4/4 15:40
* @Created by HCong
*/
public class InterfaceVsIterator {
public static void display(Iterator<Integer> it) {
System.out.println("display Iterator");
while (it.hasNext()) {
Integer next = it.next();
System.out.print(next + " ");
}
System.out.println();
}
public static void display(Collection<Integer> coll) {
System.out.println("display Collection");
for (Integer i : coll) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8);
display(list.iterator());
display(list);
}
}
display Iterator
1 2 3 4 5 6 7 8
display Collection
1 2 3 4 5 6 7 8
2 for-in 与迭代器
使用 for-in
是所有 Collection
对象的特征,原因是 Java 5
引入了一个名为 Iterable
的接口,该接口包含一个能够生成 Iterator
的 iterator()
方法。
package com.hcong.collections;
import java.util.Iterator;
/**
* @Classname IterableClass
* @Date 2023/4/5 14:40
* @Created by HCong
*/
public class IterableClass implements Iterable<String> {
protected String[] words = "And that is how we know the Earth to be banana-shaped.".split(" ");
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < words.length;
}
@Override
public String next() {
return words[index++];
}
};
}
public static void main(String[] args) {
IterableClass strings = new IterableClass();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
System.out.println("==============================");
for (String s : new IterableClass()) {
System.out.print(s + " ");
}
}
}
And that is how we know the Earth to be banana-shaped.
==============================
And that is how we know the Earth to be banana-shaped.
但是,Map
并未继承该接口。因此,Map
的遍历一般将其转换为 Set
:
package com.hcong.collections;
import java.util.Map;
/**
* @Classname EnvironmentVariables
* @Date 2023/4/5 14:54
* @Created by HCong
*/
public class EnvironmentVariables {
public static void main(String[] args) {
for (Map.Entry entry : System.getenv().entrySet()) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}