J2ME Record Management System (RMS) 提供 RecordEnumeration 遍歷記錄,構造函數支援三個參數實現篩選、排序與同步控制:
RecordEnumeration enumerateRecords(RecordFilter filter, RecordComparator comparator, boolean keepUpdated)
| 參數 | 類型 | 功能 | 預設行為 |
|---|---|---|---|
| filter | RecordFilter | 篩選記錄,實作 matches(byte[]) 返回 true 保留 | null:不篩選,返回所有記錄 |
| comparator | RecordComparator | 排序記錄,實作 compare(byte[], byte[]) 返回 PRECEDES/FOLLOWS/EQUIVALENT | null:依記錄 ID 順序 |
| keepUpdated | boolean | true:追蹤 RMS 資料變動,即時反映增刪改;false:靜態快照,效能較好 | false(建議) |
public interface RecordFilter {
boolean matches(byte[] candidate);
}
public class HelloFilter implements RecordFilter {
public boolean matches(byte[] rec) {
String str = new String(rec);
return "Hello".equals(str);
}
}
RecordStore rs = ...; // 開啟/建立 RecordStore
RecordFilter filter = new HelloFilter();
RecordEnumeration re = rs.enumerateRecords(filter, null, false);
if (re.hasNextElement()) {
int recordId = re.nextRecordId();
// 處理記錄...
}
re.destroy(); // 釋放資源
public interface RecordComparator {
int compare(byte[] rec1, byte[] rec2);
// 返回值常數:
int PRECEDES = 0; // rec1 在 rec2 之前
int FOLLOWS = 1; // rec1 在 rec2 之後
int EQUIVALENT = 2; // 位置相等
}
public class StringComparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String s1 = new String(rec1);
String s2 = new String(rec2);
int result = s1.compareTo(s2);
if (result == 0) return EQUIVALENT;
return result < 0 ? PRECEDES : FOLLOWS;
}
}
RecordComparator comparator = new StringComparator();
RecordEnumeration re = rs.enumerateRecords(null, comparator, false);
// 遍歷即為排序後順序
// 先篩選包含 "user_" 前綴的記錄,再按字串降序
RecordFilter prefixFilter = new RecordFilter() {
public boolean matches(byte[] rec) {
return new String(rec).startsWith("user_");
}
};
RecordComparator descComparator = new RecordComparator() {
public int compare(byte[] rec1, byte[] rec2) {
return new String(rec2).compareTo(new String(rec1)); // 降序
}
};
RecordEnumeration re = rs.enumerateRecords(prefixFilter, descComparator, false);
RecordEnumeration.destroy() 釋放資源,防止記憶體洩漏nextRecordId() 返回實際 IDcompare 時返回值邏輯反轉(PRECEDES/FOLLOWS 搞混)null 記錄導致 NullPointerExceptionkeepUpdated=true 導致 UI 卡頓finally 區塊呼叫 destroy()