直接贴代码
package cc.openhome;
import java.util.*;
public class ForEach {
private static void forEach(Iterable<String> iterable) {
for (Object o : iterable) {
System.out.println(o);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = Arrays.asList("Justin", "Monica", "Irene");
//forEach(list);
forEach(new HashSet<String>(list));
//forEach(new ArrayDeque<String>(list));
}
}
输出的结果如下
Monica
Justin
Irene
疑问如下
为何不是
Justin
Monica
Irene
------解决方案--------------------
HashSet无序的啊
------解决方案--------------------
HashSet是无序的。。你想按添加的顺序打印的话,需要用LinkedHashSet
------解决方案--------------------
HashSet本来就是按照哈希算法散列排序,顺序比较随机。要想按自然顺序排的话用TreeSet。想按集合对象的放入顺序排序的话应LinkedHashSet。概念问题。