我对比较器不太满意,但是我需要学习它,到目前为止我已经做了很多,但是在'System.out.println(compy(“ January”,“ March”,“ October”,“四月“));'...请帮助,我想解释一下解决方法。谢谢!
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Months {
public static void main (String args[]){
System.out.println(Comp("January","May"));
System.out.println(Comp("October", "May"));
System.out.println(Comp("August","August"));
System.out.println(Comp("January", "March"));
System.out.println(compy("January", "March", "October", "April"));
}
static int Comp(String s1, String s2){
while (true){
int r = 0;
int s = 0;
if(s1.equals("January")){
r=1;
}
if(s1.equals("February")){
r=2;
}
if(s1.equals("March")){
r=3;
}
if(s1.equals("April")){
r=4;
}
if(s1.equals("May")){
r=5;
}
if(s1.equals("June")){
r=6;
}
if(s1.equals("July")){
r=7;
}
if(s1.equals("August")){
r=8;
}
if(s1.equals("September")){
r=9;
}
if(s1.equals("October")){
r=10;
}
if(s1.equals("November")){
r=11;
}
if(s1.equals("December")){
r=12;
}
if(s2.equals("January")){
s=1;
}
if(s2.equals("February")){
s=2;
}
if(s2.equals("March")){
s=3;
}
if(s2.equals("April")){
s=4;
}
if(s2.equals("May")){
s=5;
}
if(s2.equals("June")){
s=6;
}
if(s2.equals("July")){
s=7;
}
if(s2.equals("August")){
s=8;
}
if(s2.equals("September")){
s=9;
}
if(s2.equals("October")){
s=10;
}
if(s2.equals("November")){
s=11;
}
if(s2.equals("December")){
s=12;
}
if(r<s){
return -1;
}
if(r>s){
return 1;
}
if(r==s){
return 0;
}
}
}
public class Comp implements Comparator {
public int compare(Object o1, Object o2){
return Comp((String)o1, (String)o2);
}
}
void sort(List l){
Comparator compy = new Comp();
Collections.sort(l, compy);
}
}
最佳答案
这是使用代码对列表进行排序的方式。
List<String> list = new ArrayList<String>();
list.add("March");
list.add("January");
list.add("October");
list.add("April");
System.out.println("Before sort: " + list);
// prints: Before sort: [March, January, October, April]
new Months().sort(list); // sort
System.out.println("After sort: " + list);
// prints: After sort: [January, March, April, October]
关于java - 比较器分类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18323521/