Should I use the comparable or comparator when I want to sort my list based on my own personal object? should I use the collection operation in my recycler view adapter?
Asked
Active
Viewed 2,839 times
-5
-
1Possible duplicate of [Sort listview with array adapter](http://stackoverflow.com/questions/9906464/sort-listview-with-array-adapter) – OneCricketeer Dec 22 '15 at 18:24
-
have you tried using [Google search](https://www.google.de/?gws_rd=ssl#q=how+to+sort+an+arraylist+in+java)? – Droidman Dec 22 '15 at 18:33
-
yes I tried. nevermind. I just needed an example. I cant delete this post anyway. – Eran Dec 22 '15 at 18:35
2 Answers
2
Is it a list of integers (as you specify in your title)?
you can use Arrays#sort
Arrays.sort(someArray, new Comparable<Integer>() {
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});

Tyler Sebastian
- 9,067
- 6
- 39
- 62
-
you don't need a `Comparator` (not a Comparable either) to sort integers. – njzk2 Dec 22 '15 at 18:28
-
-
well basically I have also text, but I want to sort the list by the integers that I have. ive seen this code you posted but I didn't know where should I use it.. – Eran Dec 22 '15 at 18:29
-
When you add items to your adapter, add them to the stored list and re-sort it. – Tyler Sebastian Dec 22 '15 at 18:41
2
If it's just a list of integers, and they are in for instance a List object, you don't have to use a comparator, unless you need to parse the integers as something other than plain numbers.
Collections.sort(myList);
If it's one of your own objects, look at Tyler Sebastians answer. Collections comes with a similar method for lists.
Collections.sort(myList, new MyComparator());

A.Grandt
- 2,242
- 2
- 20
- 21