你可以寫自己的類實現Comparator<RandomClass>
接口:
public class CustomComparator implements Comparator<RandomClass> {
private final AtomicInteger counter;
public CustomComparator() {
this.counter = new AtomicInteger(0);
}
@Override
public int compare(RandomClass val1, RandomClass val2) {
this.counter.incrementAndGet();
if (val1.value() < val2.value()) {
return -1;
} else if (val1.value() > val2.value()) {
return 1;
}
return 0;
}
public int getNumberOfOperations() {
return this.counter.intValue();
}
}
然後調用static <T> void sort(T[] a, Comparator<? super T> c)
功能與以下參數:
CustomComparator comparator = new CustomComparator();
Arrays.sort(randomClassAray, comparator);
System.out.println("Number of operations = " + String.valueOf(comparator.getNumberOfOperations()));
'this.comparisonCount ++;' –
寫共用輔助類含有['AtomicInteger'](https://docs.oracle.com/javase/8/docs/ api/java/util/concurrent/atomic/AtomicInteger.html)作爲計數器,將其分配給數組中的實例,並在每次比較完成時增加此計數器。 – Turing85
http://ideone.com/OzW8dB :) –