sorting custom object array on two fields
-
22-06-2021 - |
문제
I'm sorting an array of custom objects (ListData[]
) on two fields. I want it to be sorted by theme, and them by name. I thought i made a nice comparator in the custom object class and that i could use Arrays.sort(ld)
to make my code working and sorting my array. But apparently im doing something wrong...
my custom object:
public class ListData implements Comparable<ListData>{
public int venueID;
public String name;
public String photoUrl;
public String tip;
public String theme;
@Override
public int compareTo(ListData ld0) {
return this.venueID- ld0.venueID;
}
public static Comparator<ListData> ListDataThemeAndNameComparator = new Comparator<ListData>() {
@Override
public int compare(ListData ld1, ListData ld2) {
String compareTheme1 = ld1.theme.toUpperCase();
String compareTheme2= ld2.theme.toUpperCase();
String compareName1 = ld1.name.toUpperCase();
String compareName2= ld2.name.toUpperCase();
//ascending
int comp = compareTheme1.compareTo(compareTheme2); // comp themes
if(comp==0){ // same theme
comp= compareName1.compareTo(compareName2); // compare names
}
return comp;
}
};
}
And in my main activity i have:
ListData ld[]= new ListData[jsonResponse.size()];
(some code filling my ListData array)
Arrays.sort(ld, ListData.ListDataThemeAndNameComparator); // compare by theme and then by name
Does anyone know what i'm doing wrong?
I edited my code But still it fails, now on a nullpointerexception on the compareTheme1 = ld1.theme.toUpperCase();
. But i am sure my array is not empty, i logged it the line before sorting it and its filled with about 500 items.
해결책
Your ListData
object should implements Comparable
not Comparator
interface.
EDIT:
To make things clear, you can sort an array
by Array.sort()
. To make custom sort, you can specify your comparator in Array.sort()
, if you don't do that, array will be sorted in natural order which you can define by implementing Comparable
interface. So you have two options how to custom sort:
- by using custom comparator and specifying it in
Array.sort()
- by implementing
Comparable
interface to your items
I would suggest you to go with implementing Comparable
. You save memory by not creating new comparator objects and Comparator
is useful if you are comparing objects of different types which is not your case.