import java.util.Arrays;
import java.util.Comparator;public class StaticInnerClassDemo {
public static void main(String[] args) {
String[] names = {"郭","郭美","郭美美"};
Arrays.sort(names, new ByLength());
System.out.println(Arrays.toString(names));
}
static class ByLength implements Comparator<String> {
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
}上面的代码Arrays.sort(names, new ByLength())为什么会调用compare函数,而函数又是怎么对names数组进行排序的呢?
import java.util.Comparator;public class StaticInnerClassDemo {
public static void main(String[] args) {
String[] names = {"郭","郭美","郭美美"};
Arrays.sort(names, new ByLength());
System.out.println(Arrays.toString(names));
}
static class ByLength implements Comparator<String> {
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
}上面的代码Arrays.sort(names, new ByLength())为什么会调用compare函数,而函数又是怎么对names数组进行排序的呢?
不就是个参数名吗。。
不就是个参数名吗。。哦,哈哈,谢谢你。
/**
* Sorts the specified array of objects according to the order induced by
* the specified comparator. All elements in the array must be
* <i>mutually comparable</i> by the specified comparator (that is,
* <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt>
* for any elements <tt>e1</tt> and <tt>e2</tt> in the array).<p>
*
* This sort is guaranteed to be <i>stable</i>: equal elements will
* not be reordered as a result of the sort.<p>
*
* The sorting algorithm is a modified mergesort (in which the merge is
* omitted if the highest element in the low sublist is less than the
* lowest element in the high sublist). This algorithm offers guaranteed
* n*log(n) performance.
*
* @param a the array to be sorted
* @param c the comparator to determine the order of the array. A
* <tt>null</tt> value indicates that the elements'
* {@linkplain Comparable natural ordering} should be used.
* @throws ClassCastException if the array contains elements that are
* not <i>mutually comparable</i> using the specified comparator.
*/
public static <T> void sort(T[] a, Comparator<? super T> c) {
T[] aux = (T[])a.clone();
if (c==null)
mergeSort(aux, a, 0, a.length, 0);
else
mergeSort(aux, a, 0, a.length, 0, c);
}
Arrays.sort(names, bl);
从 public static <T> void sort(T[] a, Comparator<? super T> c), 你可以蒙出来new ByLength()是Comparator<? super T>
sort(String[] a, Comparator<String> c) sort要的参数类型是 Comparator<String>.Comparator<T> 里的T是String(这不叫参数).
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
public static <T> void sort(T[] a, Comparator<? super T> c)