I know there are many similar questions as mine, but I have not gotten anywhere with those answers ( I feel like I'm missing something...) But anyways:
I have a LinkedList . In my program, the user should be able to sort the list according to the files' last modified time.
I have for example tried to implement something according to these two : Finding the 3 most recently modified files in a long list of files and Get files in a directory sorted by last modified? in my program, but I don't seem to get the list sorted anyhow.
For the first link : what is the deal with returning 1, -1, or 0? Does it actually do anything, or should I add some code to either move it up or down the list?
I guess either one of those is something I should be using, right? I was wondering if that code would be enough, or do I have to add something more to get it working?
NB. I would like to create a new method, in the existing class.
So here is what i tried to do:
public static final Comparator<File> lastModified = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.lastModified() == o2.lastModified() ? 0 : (o1.lastModified() < o2.lastModified() ? 1 : -1);
}
};
public void testFileSort() {
File[] file = new File(".").listFiles();
Arrays.sort(file, lastModified);
//a snippet to actually update what the user sees
}
EDIT My biggest problem (maybe?) is that when my method is done, it does update the view, but not in the right way : the "old" list is still the same, but at the bottom there is something there shouldn't be... :
(imagelist.txt is a textfile where the imagepaths are stored), for some reason that is the list I can see after updating the view.
EDIT 2 File[] file = new File(".").listFiles();
Output: [Ljava.io.File;@3e2a9a49 So I guess this would be the ACTUAL problem...? What I was trying to do was to put the files from my LinkedList to this array, but I guess I did something wrong, got this snippet from the first link... What would be the appropriate way to do this, if this is anywhere near a proper way to go.
Thank you in advance, hope my question made some sense and you guys don't judge me too much :) I know I made this quite confusing now...
The code in your first link is enough just use Linked list instead of files array. Actually the comparison is taking place inside the comparator. To make the comparator generic it only needs to know whether the next element is bigger, or smaller or equal. It does not require to know any details about the element itself. So, in the comparator function you are handling the logic (last modified time is earlier or not) and based on that sending information to the comparator logic with 1,-1, or 0 to let it know that it is bigger, smaller or equal to the compared element. Hope this makes sense.