J2ME:rms的排序

对rms中的数据进行排序,主要是要继承RecordComparator接口,实现compare(byte[] arg0, byte[] arg1)方法,其中排序是:

设arg0为前一条数据,arg1为后一条数据

RecordComparator.FOLLOWS; //arg0放到arg1的后面
RecordComparator.PRECEDES; //arg0放到arg1的前面
RecordComparator.EQUIVALENT; //arg0和arg1无分先后

 

例子:

import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import javax.microedition.rms.RecordComparator; import javax.microedition.rms.RecordEnumeration; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreFullException; import javax.microedition.rms.RecordStoreNotFoundException; public class compareRecord extends MIDlet implements RecordComparator { RecordStore rs = null; public compareRecord() { // TODO Auto-generated constructor stub } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub } protected void pauseApp() { // TODO Auto-generated method stub } protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub try { rs = RecordStore.openRecordStore("rs", true); rs.addRecord("123".getBytes(), 0, "123".getBytes().length); rs.addRecord("78".getBytes(), 0, "78".getBytes().length); rs.addRecord("490".getBytes(), 0, "490".getBytes().length); rs.addRecord("23".getBytes(), 0, "23".getBytes().length); rs.addRecord("354".getBytes(), 0, "354".getBytes().length); RecordEnumeration re = rs.enumerateRecords(null, this, false); //能发现失效的ID并自动跳过 while (re.hasNextElement()) { System.out.println(new String(re.nextRecord())); } rs.closeRecordStore(); } catch (RecordStoreFullException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RecordStoreNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RecordStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int compare(byte[] arg0, byte[] arg1) { // TODO Auto-generated method stub int num1 = Integer.parseInt(new String(arg0)); int num2 = Integer.parseInt(new String(arg1)); if (num1 < num2) return RecordComparator.FOLLOWS; //arg0放到arg1的后面 else if (num2 < num1) return RecordComparator.PRECEDES; //arg0放到arg1的前面 return RecordComparator.EQUIVALENT; //arg0和arg1无分先后 } }

 

 

你可能感兴趣的:(J2ME:rms的排序)