Posted on 2009-12-30 14:20
java小爬虫 阅读(1622)
评论(0) 编辑 收藏
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSortTest {
/**
* @param args
* function:
* params :
* return :
*/
public static void main(String[] args) {
List list = new ArrayList();
list.add("131");
list.add("121");
list.add("124541");
list.add("151");
list.add("151a");
list.add("151b");
list.add("1");
list.add("1a");
list.add("11111");
System.out.println("********排序前************");
for (Object object : list) {
System.out.println(object.toString());
}
System.out.println("********第一次排序结果************");
Collections.sort(list);
for (Object object : list) {
System.out.println(object.toString());
}
System.out.println("********最终排序结果************");
sort(list);
for (Object object : list) {
System.out.println(object.toString());
}
}
public static List sort(List list){
for(int i = 0 ;i<list.size()-1;i++){
for(int j = 1 ;j<list.size()-i;j++){
int x = compare(list.get(j-1),list.get(j));
if(x == 1){
Object obj = null ;
obj = list.get(j-1);
list.set(j-1, list.get(j));
list.set(j, obj);
}
}
}
return list ;
}
public static int compare(Object o1, Object o2) {
double a = 0.0;
double b = 0.0;
try {
a = Double.parseDouble(o1.toString());
b = Double.parseDouble(o2.toString());
} catch (Exception e) {
//System.out.println("类型转换错误!");
}
if(a!=0.0&&b!=0.0){
if(a>b) return 1;
return -1 ;
}
return 0 ;
}
}
结果打印:
********排序前************
131
121
124541
151
151a
151b
1
1a
11111
********第一次排序结果************
1
11111
121
124541
131
151
151a
151b
1a
********最终排序结果************
1
121
131
151
11111
124541
151a
151b
1a