希望 compare() 方法的这些实现可以帮助您更好地理解它。
public int compare(Object obj1, Object obj2)
{
Integer I1 = (Integer)obj1; // typecasting object type into integer type
Integer I2 = (Integer)obj2; // same as above ..
// 1.
return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]
// 2.
return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]
// 3.
return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]
// 4.
return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]
// 5.
return +1; // insertion order [10, 0, 15, 5, 20, 20]
// 6.
return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]
// 7.
return 0; // only first element [10]
}
compare() 方法在 Java 中的工作原理