日期:2014-05-20  浏览次数:20730 次

ArrayList排序加跌代器遍例
用ArrayList添加 "b "   "c "   "a "   "d "   "f "     "e "   .对ArrayList排序然后用Iterator遍例打印输出.     我怎么排好序一遍例排序就没了.谁能给写个详细的例子啊?

------解决方案--------------------
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;


public class Test {

public void printArrayList()
{
ArrayList list = new ArrayList();
list.add( "c " );
list.add( "b " );
list.add( "a " );
list.add( "f " );
list.add( "e " );
list.add( "d " );

Collections.sort( list, new MyComp() );

Iterator it = list.iterator();
while( it.hasNext() )
System.out.println( (String)it.next() );
}

public static void main(String[] args)
{

new Test().printArrayList();

}

private class MyComp implements Comparator
{
public int compare(Object o1, Object o2)
{
return o1.toString().compareTo( o2 );
}
}

}