How can I efficiently add/delete/get sorted data in Java?

I am writing a telephone directory program and need to store the entries in a CSV formatted file. However, I am having difficulty keeping the entries in order when adding. I was considering reading in the entire file to an array of entries and then write it back out when the program exists, but this seems inefficient. Is there a straightforward approach to adding entries to a sorted file?


Your first instinct is correct: sort the entire thing in memory, then write it out. Performing line-oriented I/O to read and write the file will be far more inefficient than doing a bulk read and write of the entire file.

My two cents:

  • Don’t save to a file.
  • Save to a SQLite database table
  • Create an index for that table
  • The SQLite library maintains the index sorted and reports are sorted even when the data is not.
  • You can programativally export to CSV whenever you want.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *