1
此代碼完美工作,但不幸的是,由於Arrays.sort()比較器的原因,它會觸發垃圾收集。2維數組上的Arrays.sort沒有觸發垃圾收集?
有沒有辦法做到這一點,不會觸發垃圾收集?
(注:此代碼已被修改爲更加「通用」的實際代碼是一個Android遊戲,這就是爲什麼垃圾收集引起的經濟放緩是一個問題。)
static final byte INCOME = 0;
static final byte INDEX = 1;
public void vSortEmployees() {
nPaidEmployees = 0;
for (nIter=0; nIter<MAX_EMPLOYEES; nIter++) {
if ((employees[nIter].current == true) && (employees[nIter].volunteer == false)) {
// We have another current and paid employee; add that employee's "amount earned to date" to the list.
paidemployees[nPaidEmployees][INCOME] = employees[nIter].fGetTotalIncomeToDate();
paidemployees[nPaidEmployees][INDEX] = nIter;
nPaidEmployees++;
}
}
Arrays.sort(paidemployees, new Comparator<float[]>() {
@Override
public int compare(float[] f1, float[] f2) {
if (f2[INCOME] < f1[INCOME])
return -1;
else if (f2[INCOME] > f1[INCOME])
return 1;
else
return 0;
}
});
// Now we have a list of current, paid employees in order of income received.
// Highest income paid out
paidemployees[0][INCOME]
// Second highest income paid out
paidemployees[1][INCOME]
// If we need to reference the original employee object, we can:
employees[paidemployees[0][INDEX]].getName();
}
有沒有可能的方式,_comparator_可能導致足夠的垃圾成爲你的瓶頸。但無論如何,爲什麼不把'Comparator'存儲在一個靜態的最終字段呢?另外,爲什麼你使用數組而不是適當的'Employee'對象? –