问题
I have a task to sort files (list of files), dependng on user input by name, size, date modified, size, type, and other types of conditions can be added in future.
So if user inputs "dir /sort=esdn" (extension, size, date, name) That means sort by extension, where program can't decide sort by size...
I thougth it would be messy to have all those comparators in same class or as lambda expressions, so i had idea of creating a new clas where all comparisons code would be
public class Comparisons {
public class Ext implements Comparator<File> {
...
}
public class Size implements Comparator<File> {
...
}
public class Date implements Comparator<File> {
...
}
public class Name implements Comparator<File> {
...
}
public class Type implements Comparator<File> {
...
}
}
And I have idea how to run it and all, but I can't seem to find a way to create new inner class without creating outer class first. It seems to me that Java would have something like that as it foucuses a lot on sytax sugar, best alterntative would be new package.
Rest of the code would be recursive function that sorts by first letter
private boolean sort(String substring, List<File> fin) {
Comparator<File> k = null;
char in = substring.toLowerCase().charAt(0);
switch (in) {
case n:
k = Comparisons.new Name();
break;
case e:
k = Comparisons.new Ext();
break;
case s:
k = Comparisons.new Size();
break;
case d:
k = Comparisons.new Date();
break;
case t:
k = Comparisons.new Type();
break;
default:
break;
}
...
}
I know this doesn't work but that's the general idea of what I want to achieve.
Thanks a lot!
回答1:
You can use an enum
:
public enum FileComparator implements Comparator<File> {
DateComparator {
@Override
public int compare(File o1, File o2) {
// TODO Auto-generated method stub
return 0;
}
},
SizeComparator {
@Override
public int compare(File o1, File o2) {
// TODO Auto-generated method stub
return 0;
}
},
NameComparator {
@Override
public int compare(File o1, File o2) {
// TODO Auto-generated method stub
return 0;
}
}
}
Each element in the enum
can have its own version of the compare
method and you won't need to create any classes, but still you can use it like normal class:
Comparator<File> comp = FileComparator.NameComparator;
//use the comparator
来源:https://stackoverflow.com/questions/27784735/class-to-store-multiple-comparators