本帖最后由 追逐 于 2014-3-25 14:40 编辑
- import java.util.Collections;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.Comparator;
- class CollectionsDemo
- {
- public static void main(String[] args)
- {
- listSort();
- }
- public static void listSort()
- {
- List<String> al = new ArrayList<String>();
- al.add("abcd");
- al.add("a");
- al.add("abc");
- al.add("efang");
- al.add("ge");
- Iterator<String> it = al.iterator();
- for( ; it.hasNext(); )
- {
- String s = it.next(); //为什么这样做就不能正常程排序了呢?求解
- Collections.sort(al, new Comp());
- System.out.println(s);
- }
- /*//为什么这么做就可以呢?
- for( ; it.hasNext(); )
- {
- Collections.sort(al, new Comp());
- System.out.println(it.next());
- }*/
- }
- }
- class Comp implements Comparator<String>
- {
- public int compare(String s1, String s2)
- {
- if(s1.length() > s2.length())
- return 1;
- if(s1.length() < s2.length())
- return -1;
- return s1.compareTo(s2);
- }
- }
复制代码 为什么第二个for循环中能打印正确结果。而第一个for循环打印的结果却是错误的。而且结果令我很费解
下面有第一个for循环输出的结果。求大神帮忙分析一下。
|