0

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!

Roger Travis
  • 8,402
  • 18
  • 67
  • 94

3 Answers3

7

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
kosa
  • 65,990
  • 13
  • 130
  • 167
2

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());
Byter
  • 1,132
  • 1
  • 7
  • 12
0

Implement a Comparator<fileObj> and sort the list using Collections.sort(list, comparator); method

kgautron
  • 7,915
  • 9
  • 39
  • 60