Say I have an ArrayList of custom object, such as
class fileOjb
{
String path;
String format;
int size;
int dateadd;
}
How should I sort it by - path, format, size or dateadded?
Thanks!
Say I have an ArrayList of custom object, such as
class fileOjb
{
String path;
String format;
int size;
int dateadd;
}
How should I sort it by - path, format, size or dateadded?
Thanks!
You need to write your own comparator and call Collections.sort(yourComparator)
For example:
class YourComparator implements Comparator<MyObj>{
public int compare(MyObj o1, MyObj o2) {
return o1.getyourAtt() - o2.getyourAtt();
}
}
NOTE: Cast o1 and 02 to your object type.
EDIT: Based on Ted comment, update to generics, now don't need cast
Here is the code example.for sorting by dateAdded
.
for sorting by other properties..you have to first decide your criteria
.
(what is criteria for String path1
to be greater than path2
)
public class MyComparableByDateAdded implements Comparator<fileOjb>{
@Override
public int compare(fileOjb o1, fileOjb o2) {
return (o1.dateAdd>o2.dateAdd ? -1 : (o1.dateAdd==o2.dateAdd ? 0 : 1));
}
}
Collections.sort(list, new MyComparableByDateAdded());
Implement a Comparator<fileObj>
and sort the list using Collections.sort(list, comparator)
; method