I am writing an application for Android mobile phones.
I have a java.util.ArrayList
that contains objects which require a custom java.util.Comparator
to be sorted properly.
I know I can use java.util.Collections.sort()
but the amount of data is such that I want to sort my ArrayList
in an android.os.AsyncTask
.
I do not want to use several AsyncTask objects that would each sort a subset of the data.
Any AsyncTask can be cancelled so I want to regularly call AsyncTask.isCancelled()
while I sort. If it returns true, I give up on sorting (and on my whole data set).
I Googled but could not find an AsyncTask-friendly way to sort while regularly checking for cancellation.
I may be able to call isCancelled()
in my implementation of java.util.Comparator.compare()
and throw my own subclass of java.lang.RuntimeException
if it returns true. Then try{java.util.Collections.sort(ArrayList, Comparator);} catch () {}
for that specific exception. I don't feel entirely comfortable with that approach.
Alternatively, I can use an intermediary java.util.TreeSet
and write 2 loops that each check for cancellation before every iteration. The first loop would add all the items of the ArrayList
to the TreeSet
(and my Comparator
implementation keeps them sorted on insertion). The second loop would add all the object in the TreeSet
back into the ArrayList
, in the correct order, thanks to the TreeSet
natural java.util.Iterator
. This approach uses some extra memory but will assuredly work.
The last approach I can think of is to implement myself what I have actually been looking for in Android: A generic java.util.List
(preferably quick)sort using a java.util.Comparator
and an android.os.AsyncTask
that regularly checks for cancellation.
Has anybody found that?
Do you have any other solution to this problem?
EDIT:
Although I haven't given any thought to what the sorting method signature would look like, I would also be perfectly happy with using a android.os.CancellationSignal
to decide when to abandon the sorting.