comparator:实现Comparator接口来进行字符串逆向排序

例子代码如下:

// Create a Comparator that s the outcome
// of a reverse comparison.
RevStrComp implements Comparator<String> {
// Implement the compare method so that it
// reverses the order of the comparison.
public compare(String strA, String strB) {// Compare strB to strA, rather than strA to strB.
strB.compareTo(strA);
}
}

// Sort an .gif' /> of s in reverse order.
import java.util.*;
// Create a Comparator that s the outcome
// of a reverse comparison.
RevStrComp implements Comparator<String> {
// Implement the compare method so that it
// reverses the order of the comparison.
public compare(String strA, String strB) {
// Compare strB to strA, rather than strA to strB.
strB.compareTo(strA);
}
}
// Demonstrate the reverse comparator.
RevStrSort {
public void (String args) {
// Create a sample .gif' /> of s.
String strs = { "dog", "horse", "zebra", "cow", "cat" };
// Show the initial order.
.out.pr("Initial order: ");
for(String s : strs)
.out.pr(s + " ");
.out.prln("\n");
// Sort the .gif' /> in reverse order.
// Begin by creating a reverse comparator.
RevStrComp rsc = RevStrComp;

// Now, sort the s using the reverse comparator.
Arrays.sort(strs, rsc);
// Show the reverse sorted order.
.out.pr("Sorted in reverse order: ");
for(String s : strs)
.out.pr(s + " ");
.out.prln("\n");
// For comparison, sort the s in natural order.
Arrays.sort(strs);
// Show the natural sorted order.
.out.pr("Sorted in natural order: ");
for(String s : strs)
.out.pr(s + " ");
.out.prln("\n");
}
}

输出为:

Initial order: dog horse zebra cow cat
Sorted in reverse order: zebra horse dog cow cat
Sorted in natural order: cat cow dog horse zebra

Tags:  java字符串排序 字符串排序 javacomparator comparator

延伸阅读

最新评论

发表评论