67,513
社区成员
发帖
与我相关
我的任务
分享
package com.eleven.intefacee;
import java.util.Arrays;
import java.util.Comparator;
public class LengthComparator implements Comparator<String>{
// 按照长度比较字符串
public int compare(String first, String second) {
return first.length() - second.length();
}
public static void main(String[] args) {
String[] friends = {"Peter", "Paul", "Mary"};
Comparator<String> comp = new LengthComparator();
//if (comp.compare(words[i], words[j]) > 0) {
Arrays.sort(friends, new LengthComparator());
// }
}
}
// 按照长度比较字符串
public int compare(String first, String second) {
return first.length() - second.length();
}
public static void main(String[] args) {
String[] friends = {"Peter", "Paul", "Mary"};
System.out.println("排序前打印");
for(int i=0;i<friends.length;i++) {
System.out.print(friends[i]+" ");
}
System.out.println("\n排序后打印");
Arrays.sort(friends, new LengthComparator());
for(int i=0;i<friends.length;i++) {
System.out.print(friends[i]+" ");
}
}