import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Sort implements Comparator<String> {
private final static int UP = 1;
private final static int DOWM = -1;
private int state;
public Sort(int state) {
this.state = state;
}
public Sort() {
}
public int compare(String o1, String o2) {
if (state == Sort.DOWM) {
return sortDown(o1, o2);
}
return sortUp(o1, o2);
}
private int sortUp(String o1, String o2) {
if (o1.compareTo(o2) < 0) {
return -1;
} else if (o1.compareTo(o2) > 0) {
return 1;
} else {
return 0;
}
}
private int sortDown(String o1, String o2) {
if (o1.compareTo(o2) > 0) {
return -1;
} else if (o1.compareTo(o2) < 0) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("000001");
array.add("000003");
array.add("000005");
array.add("000004");
array.add("000002");
Collections.sort(array, new Sort(Sort.DOWM));
for (String str : array) {
System.out.println(str);
}
}
}
import java.util.Collections;
import java.util.Comparator;
public class Sort implements Comparator<String> {
private final static int UP = 1;
private final static int DOWM = -1;
private int state;
public Sort(int state) {
this.state = state;
}
public Sort() {
}
public int compare(String o1, String o2) {
if (state == Sort.DOWM) {
return sortDown(o1, o2);
}
return sortUp(o1, o2);
}
private int sortUp(String o1, String o2) {
if (o1.compareTo(o2) < 0) {
return -1;
} else if (o1.compareTo(o2) > 0) {
return 1;
} else {
return 0;
}
}
private int sortDown(String o1, String o2) {
if (o1.compareTo(o2) > 0) {
return -1;
} else if (o1.compareTo(o2) < 0) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("000001");
array.add("000003");
array.add("000005");
array.add("000004");
array.add("000002");
Collections.sort(array, new Sort(Sort.DOWM));
for (String str : array) {
System.out.println(str);
}
}
}
本文提供了一个Java排序示例,展示了如何使用自定义比较器对字符串列表进行升序和降序排列。通过创建Sort类实现Comparator接口,并根据指定的状态对字符串进行排序。
3057

被折叠的 条评论
为什么被折叠?



