24/05/2018, 22:25

Sắp xếp các record với interface RecordComparator

Interface này giúp người lập trình so sánh hai Record theo một tiêu chí nào đó. Interface này định nghĩa phương thức compare với trị đầu vào là hai mảng các byte thể hiện hai Record cần so sánh. Phương thức này trả về các trị sau được định nghĩa trong ...

Interface này giúp người lập trình so sánh hai Record theo một tiêu chí nào đó. Interface này định nghĩa phương thức compare với trị đầu vào là hai mảng các byte thể hiện hai Record cần so sánh. Phương thức này trả về các trị sau được định nghĩa trong interface:

• EQUIVALENT: Nếu hai Record bằng nhau

• FOLLOWS: Nếu Record thứ 1 đứng sau Record thứ 2

• PRECEDES: Nếu Record thứ 1 đứng trước Record thứ 2

Do RecrdComparator là một interface nên khi sử dụng cần phải implements nó:

public class Comparator implements RecordComparator

{

public int compare(byte[] rec1, byte[] rec2)

{

String str1 = new String(rec1), str2 = new String(rec2);

int result = str1.compareTo(str2);

if (result == 0)

return RecordComparator.EQUIVALENT;

else if (result < 0)

return RecordComparator.PRECEDES;

else

}

}

return RecordComparator.FOLLOWS;

Sau đó ta sử dụng lớp Comparator bằng cách gắn kết nó với RecordEnumeration:

// Create a new comparator for sorting

Comparator comp = new Comparator();

// Reference the comparator when creating the result set

RecordEnumeration re = rs.enumerateRecords(null,comp,false);

// Iterate through the sorted results while (re.hasNextElement())

{

String str = new String(re.nextRecord());

.

Enumeration sẽ sử dụng hàm compare trong class Comparator để sắp xếp các record trong RecordStore.

Ví dụ 3: chương trình sắp xếp cơ bản

/*--------------------------------------------------

* SimpleSort.java

*

* No GUI interface, all output is to the console

*-------------------------------------------------*/

import java.io.*;

import javax.microedition.midlet.*;

import javax.microedition.rms.*;

public class SimpleSort extends MIDlet

{

private RecordStore rs = null;

static final String REC_STORE = "db_1";

public SimpleSort()

{

openRecStore(); // Create the record store

// Write a few records

writeRecord("Sand Wedge");

writeRecord("One Wood");

writeRecord("Putter");

writeRecord("Five Iron");

// Read back with enumerator, sorting the results

readRecords();

closeRecStore(); // Close record store deleteRecStore(); // Remove the record store

}

public void destroyApp( boolean unconditional )

{

}

public void startApp()

{

// There is no user interface, go ahead and shutdown

destroyApp(false);

notifyDestroyed();

}

public void pauseApp()

{

}

public void openRecStore()

{

try

{

// Create record store if it does not exist

rs = RecordStore.openRecordStore(REC_STORE, true );

}

catch (Exception e)

{

db(e.toString());

}

}

public void closeRecStore()

{

try

{

rs.closeRecordStore();

}

catch (Exception e)

{

db(e.toString());

}

}

public void deleteRecStore()

{

if (RecordStore.listRecordStores() != null)

{

try

{

RecordStore.deleteRecordStore(REC_STORE);

}

catch (Exception e)

{

db(e.toString());

}

}

}

public void writeRecord(String str)

{

byte[] rec = str.getBytes();

try

{

rs.addRecord(rec, 0, rec.length);

}

catch (Exception e)

{

db(e.toString());

}

}

public void readRecords()

{

try

{

if (rs.getNumRecords() > 0)

{

Comparator comp = new Comparator();

RecordEnumeration re = rs.enumerateRecords(null,comp, false);

while (re.hasNextElement())

{

String str = new String(re.nextRecord());

System.out.println(str);

System.out.println("------------------------------");

}

}

}

catch (Exception e)

{

db(e.toString());

}

}

/*--------------------------------------------------

* Simple message to console for debug/errors

* When used with Exceptions we should handle the

* error in a more appropriate manner.

*-------------------------------------------------*/

private void db(String str)

{

System.err.println("Msg: " + str);

}

}

/*--------------------------------------------------

| Comparator.java

|

| Compares two records to determine sort order

*-------------------------------------------------*/

class Comparator implements RecordComparator

{

public int compare(byte[] rec1, byte[] rec2)

{

String str1 = new String(rec1), str2 = new String(rec2);

int result = str1.compareTo(str2);

if (result == 0)

return RecordComparator.EQUIVALENT;

else if (result < 0)

return RecordComparator.PRECEDES;

else

return RecordComparator.FOLLOWS;

}

}

Trong đoạn code trên trong hàm readRecord(), khi tạo Enumeration ta đã tham chiếu

đến đối tượng comp của lớp Comparator

Comparator comp = new Comparator(); RecordEnumeration re = rs.enumerateRecords(null, comp, false);

while (re.hasNextElement())

{

...

}

Khi enumerator tạo index cho RecordStore nó sẽ sử dụng hàm compare() ở trên để sắp xếp các record.

Output của vi dụ 3:

Ví dụ trên đúng trong trường hợp dữ liệu lưu vào record là dạng text, nếu quay lại ví dụ

2 ta đã ghi nhiều kiểu dữ liệu vào trong một record:

// Write Java data types to stream strmDataType.writeUTF("Text 1"); strmDataType.writeBoolean(true); strmDataType.writeInt(1);

Các kiểu dữ liệu trên sẽ được lưu vào một stream ở dạng binary. Sau đó các stream này sẽ được chuyển thành mảng và đưa vào recordstore:

// Get stream data into an array record = strmBytes.toByteArray();

// Write the array to a record rs.addRecord(record, 0, record.length);

Đoạn code trong ví dụ 3 sẽ chạy sai khi áp dụng với kiểu dữ liệu binary. Để giải quyết, ta cần phải viết lại hàm compare() thự c hiện chức năng chuyển đổi chuỗi byte và sắp xếp đúng kiểu dữ liệu.

Trong thực tế, chúng ta cần phải lưu nhiều trường dữ liệu trong một record như trong ví dụ 2 (lưu dữ liệu kiểu String, boolean, integer). Trong trường hợp này sẽ có nhiều lựa chọn để sắp xếp các record, và việc lựa chọn này tùy thuộc vào ứng dụng của bạn.

Trong 2 ví dụ sau đây sẽ thực thi interface RecordComparator để sắp xếp record chứa nhiều kiểu dữ liệu. Những ví dụ này sẽ sử dụng cùng dữ liệu đầu vào, tuy nhiên ví dụ 4 sẽ sắp xếp dựa vào kiểu String, trong khi ví dụ 5 sẽ sắp xếp dựa vào kiểu integer. Đây là dữ liệu sẽ lưu vào recordstore:

String[] pets = {"duke", "tiger", "spike", "beauregard"};

boolean[] dog = {true, false, true, true};

int[] rank = {3, 0, 1, 2};

Khi lưu vào recordstore sẽ có dạng như sau: Record #1

"duke" true 3

Record #2

"tiger" false 0

Record #3

"spike" true 1

Record #4

"beauregard" true 2

Đây là lý do ví dụ 3 không đáp ứng được yêu cầu, do dữ liệu lưu vào không còn là dạng text, và hàm String.CompareTo() trên nội dung của record không thể sắp xếp dữ liệu theo mong muốn. Do đó, bạn cần phải lấy ra từ mỗi record trường dữ liệu mà bạn muốn sắp xếp. Trong ví dụ 4 sẽ lấy kiểu String ở đầu mỗi record, ví dụ 5 sẽ lấy kiểu integer ở cuối mỗi record.

Ví dụ 4: StringSort.java

/*--------------------------------------------------

* StringSort.java

*

* Sort records that contain multiple Java

* data types. Sort using String type.

*

* Uses: Streams, Enumeration, RecordComparator

*

* No GUI interface, all output is to the console

*-------------------------------------------------*/

import java.io.*;

import javax.microedition.midlet.*;

import javax.microedition.rms.*;

public class StringSort extends MIDlet

{

private RecordStore rs = null; // Record store

static final String REC_STORE = "db_3"; // Name of record store

public StringSort()

{

openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store

}

public void destroyApp( boolean unconditional )

{

}

public void startApp()

{

// There is no user interface, go ahead and shutdown

destroyApp(false);

notifyDestroyed();

}

public void pauseApp()

{

}

public void openRecStore()

{

try

{

// Create record store if it does not exist

rs = RecordStore.openRecordStore(REC_STORE, true );

}

catch (Exception e)

{

db(e.toString());

}

}

public void closeRecStore()

{

try

{

rs.closeRecordStore();

}

catch (Exception e)

{

db(e.toString());

}

}

public void deleteRecStore()

{

if (RecordStore.listRecordStores() != null)

{

try

{

RecordStore.deleteRecordStore(REC_STORE);

}

catch (Exception e)

{

db(e.toString());

}

}

}

/*--------------------------------------------------

* Create three arrays to write to record store

*-------------------------------------------------*/

public void writeTestData()

{

String[] pets = {"duke", "tiger", "spike", "beauregard"};

boolean[] dog = {true, false, true, true};

int[] rank = {3, 0, 1, 2};

writeStream(pets, dog, rank);

}

/*--------------------------------------------------

* Write to record store using streams.

*-------------------------------------------------*/

public void writeStream(String[] sData, boolean[] bData,int[] iData)

{

try

{

// Write data into an internal byte array

ByteArrayOutputStream strmBytes =

new ByteArrayOutputStream();

// Write Java data types into the above byte array

DataOutputStream strmDataType =

new DataOutputStream(strmBytes);

byte[] record;

for (int i = 0; i < sData.length; i++)

{

// Write Java data types

strmDataType.writeUTF(sData[i]);

strmDataType.writeBoolean(bData[i]);

strmDataType.writeInt(iData[i]);

// Clear any buffered data

strmDataType.flush();

// Get stream data into byte array and write record

record = strmBytes.toByteArray();

rs.addRecord(record, 0, record.length);

// Toss any data in the internal array so writes

// starts at beginning (of the internal array)

strmBytes.reset();

}

strmBytes.close();

strmDataType.close();

}

catch (Exception e)

{

db(e.toString());

}

}

/*--------------------------------------------------

* Read from the record store using streams

*-------------------------------------------------*/

public void readStream()

{

try

{

// Careful: Make sure this is big enough!

// Better yet, test and reallocate if necessary byte[] recData = new byte[50];

// Read from the specified byte array

ByteArrayInputStream strmBytes =

new ByteArrayInputStream(recData);

// Read Java data types from the above byte array

DataInputStream strmDataType =

new DataInputStream(strmBytes);

if (rs.getNumRecords() > 0)

{

ComparatorString comp = new ComparatorString();

int i = 1;

RecordEnumeration re = rs.enumerateRecords(null,

comp, false);

while (re.hasNextElement())

{

// Get data into the byte array

rs.getRecord(re.nextRecordId(), recData, 0);

// Read back the data types

System.out.println("Record #" + i++);

System.out.println("Name: " + strmDataType.readUTF());

System.out.println("Dog: " + strmDataType.readBoolean());

System.out.println("Rank: " + strmDataType.readInt());

System.out.println("--------------------");

// Reset so read starts at beginning of array

strmBytes.reset();

}

comp.compareStringClose();

// Free enumerator

re.destroy();

}

strmBytes.close();

strmDataType.close();

}

catch (Exception e)

{

db(e.toString());

}

}

/*--------------------------------------------------

* Simple message to console for debug/errors

* When used with Exceptions we should handle the

* error in a more appropriate manner.

*-------------------------------------------------*/

private void db(String str)

{

System.err.println("Msg: " + str);

}

}

/*--------------------------------------------------

| Compares two strings to determine sort order

| Each record passed in contains multiple Java data

| types - use only the String data for sorting

*-------------------------------------------------*/

class ComparatorString implements RecordComparator

{

private byte[] recData = new byte[10];

// Read from a specified byte array

private ByteArrayInputStream strmBytes = null;

// Read Java data types from the above byte array private DataInputStream strmDataType = null; public void compareStringClose()

{

try

{

if (strmBytes != null)

strmBytes.close();

if (strmDataType != null)

strmDataType.close();

}

catch (Exception e)

{

}

}

public int compare(byte[] rec1, byte[] rec2)

{

String str1, str2;

try

{

// If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length);

if (maxsize > recData.length)

recData = new byte[maxsize];

// Read record #1

// Only need one read because the string to

// sort on is the first "field" in the record

strmBytes = new ByteArrayInputStream(rec1);

strmDataType = new DataInputStream(strmBytes);

str1 = strmDataType.readUTF();

// Read record #2

strmBytes = new ByteArrayInputStream(rec2);

strmDataType = new DataInputStream(strmBytes);

str2 = strmDataType.readUTF();

// Compare record #1 and #2

int result = str1.compareTo(str2);

if (result == 0)

return RecordComparator.EQUIVALENT;

else if (result < 0)

return RecordComparator.PRECEDES;

else

return RecordComparator.FOLLOWS;

}

catch (Exception e)

{

return RecordComparator.EQUIVALENT;

}

}

}

Trường dữ liệu đầu tiên trong các record là kiểu string, - dùng làm tiêu chí sắp xếp. Trước hết ta lấy chuỗi cần so sánh trong dãy byte bằng hàm readUTF() , rồi dùng compareTo() trong class String để sắp xếp:

// Read record #1

// Only need one read because the string to

// sort on is the first "field" in the record

. . .

str1 = strmDataType.readUTF();

// Read record #2

. . .

str2 = strmDataType.readUTF();

// Compare record #1 and #2

int result = str1.compareTo(str2);

. . .

Output của ví dụ 4:

Ví dụ 5: integer sort

/*--------------------------------------------------

* IntSort.java

*

* Sort records that contain multiple Java

* data types. Sort using integer type.

*

* Uses: Streams, Enumeration, RecordComparator

*

* No GUI interface, all output is to the console

*-------------------------------------------------*/

import java.io.*;

import javax.microedition.midlet.*; import javax.microedition.rms.*; public class IntSort extends MIDlet

{

private RecordStore rs = null; // Record store

static final String REC_STORE = "db_4"; // Name of record store

public IntSort()

{

openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store

}

public void destroyApp( boolean unconditional )

{

}

public void startApp()

{

// There is no user interface, go ahead and shutdown

destroyApp(false);

notifyDestroyed();

}

public void pauseApp()

{

}

public void openRecStore()

{

try

{

// Create record store if it does not exist

rs = RecordStore.openRecordStore(REC_STORE, true );

}

catch (Exception e)

{

db(e.toString());

}

}

public void closeRecStore()

{

try

{

rs.closeRecordStore();

}

catch (Exception e)

{

db(e.toString());

}

}

public void deleteRecStore()

{

if (RecordStore.listRecordStores() != null)

{

try

{

RecordStore.deleteRecordStore(REC_STORE);

}

catch (Exception e)

{

db(e.toString());

}

}

}

/*--------------------------------------------------

* Create three arrays to write to record store

*-------------------------------------------------*/

public void writeTestData()

{

String[] pets = {"duke", "tiger", "spike", "beauregard"};

boolean[] dog = {true, false, true, true};

int[] rank = {3, 0, 1, 2};

writeStream(pets, dog, rank);

}

/*--------------------------------------------------

* Write to record store using streams.

*-------------------------------------------------*/

public void writeStream(String[] sData, boolean[] bData,int[] iData)

{

try

{

// Write data into an internal byte array

ByteArrayOutputStream strmBytes =

new ByteArrayOutputStream();

// Write Java data types into the above byte array

DataOutputStream strmDataType =

new DataOutputStream(strmBytes);

byte[] record;

for (int i = 0; i < sData.length; i++)

{

// Write Java data types

strmDataType.writeUTF(sData[i]);

strmDataType.writeBoolean(bData[i]);

strmDataType.writeInt(iData[i]);

// Clear any buffered data

strmDataType.flush();

// Get stream data into byte array and write record

record = strmBytes.toByteArray();

rs.addRecord(record, 0, record.length);

// Toss any data in the internal array so writes

// starts at beginning (of the internal array)

strmBytes.reset();

}

strmBytes.close();

strmDataType.close();

}

catch (Exception e)

{

db(e.toString());

}

}

/*--------------------------------------------------

* Read from the record store using streams

*-------------------------------------------------*/

public void readStream()

{

try

{

// Careful: Make sure this is big enough!

// Better yet, test and reallocate if necessary byte[] recData = new byte[50];

// Read from the specified byte array

ByteArrayInputStream strmBytes =

new ByteArrayInputStream(recData);

// Read Java data types from the above byte array

DataInputStream strmDataType =

new DataInputStream(strmBytes);

if (rs.getNumRecords() > 0)

{

ComparatorInt comp = new ComparatorInt();

int i = 1;

RecordEnumeration re = rs.enumerateRecords(null,comp, false);

while (re.hasNextElement())

{

// Get data into the byte array

rs.getRecord(re.nextRecordId(), recData, 0);

// Read back the data types

System.out.println("Record #" + i++);

System.out.println("Name: " + strmDataType.readUTF());

System.out.println("Dog: " + strmDataType.readBoolean());

System.out.println("Rank: " + strmDataType.readInt());

System.out.println("--------------------");

// Reset so read starts at beginning of array

strmBytes.reset();

}

comp.compareIntClose();

// Free enumerator

re.destroy();

}

strmBytes.close();

strmDataType.close();

}

catch (Exception e)

{

db(e.toString());

}

}

/*--------------------------------------------------

* Simple message to console for debug/errors

* When used with Exceptions we should handle the

* error in a more appropriate manner.

*-------------------------------------------------*/

private void db(String str)

{

System.err.println("Msg: " + str);

}

}

/*--------------------------------------------------

| Compares two integers to determine sort order

| Each record passed in contains multiple Java data

| types - use only the integer data for sorting

*-------------------------------------------------*/

class ComparatorInt implements RecordComparator

{

private byte[] recData = new byte[10];

// Read from a specified byte array

private ByteArrayInputStream strmBytes = null;

// Read Java data types from the above byte array private DataInputStream strmDataType = null; public void compareIntClose()

{

try

{

if (strmBytes != null)

strmBytes.close();

if (strmDataType != null)

strmDataType.close();

}

catch (Exception e)

{

}

}

public int compare(byte[] rec1, byte[] rec2)

{

int x1, x2;

try

{

// If either record is larger than our buffer, reallocate int maxsize = Math.max(rec1.length, rec2.length);

if (maxsize > recData.length)

recData = new byte[maxsize];

// Read record #1

// We want the integer from the record, which is

// the last "field" thus we must read the String

// and boolean to get to the integer

strmBytes = new ByteArrayInputStream(rec1);

strmDataType = new DataInputStream(strmBytes);

strmDataType.readUTF();

strmDataType.readBoolean();

x1 = strmDataType.readInt(); // Here's our data

// Read record #2

strmBytes = new ByteArrayInputStream(rec2);

strmDataType = new DataInputStream(strmBytes);

strmDataType.readUTF();

strmDataType.readBoolean();

x2 = strmDataType.readInt(); // Here's our data

// Compare record #1 and #2

if (x1 == x2)

return RecordComparator.EQUIVALENT;

else if (x1 < x2)

return RecordComparator.PRECEDES;

else

return RecordComparator.FOLLOWS;

}

catch (Exception e)

{

return RecordComparator.EQUIVALENT;

}

}

}

Trong ví dụ này ta vẫn sẽ dùng dữ liệu của ví dụ 4, tiêu chí sắp xếp là theo kiểu integer, do đó trước hết ta phải lấy dữ liệu trong dãy byte. Tuy nhiên,,có một lưu ý là do dữ liệu ta cần lấy nằm cuối cùng trong dãy byte do đó ra cần phải đọc theo thứ tự, tức là phải đọc kiểu String, boolean rồi mới đến integer:

// Read record #1

// We want the integer from the record, which is

// the last "field" thus we must read the String

// and boolean to get to the integer

. . . strmDataType.readUTF();

strmDataType.readBoolean();

x1 = strmDataType.readInt(); // Here's our data

// Read record #2

. . . strmDataType.readUTF();

strmDataType.readBoolean();

x2 = strmDataType.readInt(); // Here's our data

// Compare record #1 and #2

. . .

Output của ví dụ 5:

0