package corejava8.structure;
import java.util.Comparator;
public class CustomComparator implements Comparator {
@Override
public int compare(String s1, String s2) {
s1 = s1.substring(1);
s2 = s2.substring(1);
return s1.compareTo(s2);
// or, more concisely:
// return s1.substring(1).compareTo(s2.substring(1));
}
}
CustomComparatorDemo.java
package corejava8.structure;
import java.util.Arrays;
public class CustomComparatorDemo {
public static void main(String[] unused) {
String[] strings = { "painful", "mainly", "gaining", "raindrops" };
Arrays.sort(strings);
dump(strings, "Using Default Sort");
Arrays.sort(strings, new CustomComparator());
dump(strings, "Using Custom Comparator");
}
static void dump(String[] args, String title) {
System.out.println(title);
for (String s : args)
System.out.println(s);
}
}
运行结果:
Using Default Sort
gaining
mainly
painful
raindrops
Using Custom Comparator
raindrops
painful
gaining
mainly
分享到:
2015-10-21 14:17
浏览 1188
评论