vorrei imparare ad usare Comparator.
questa è la mia classe:
so che devo implementare uno dei due metodi di comparator.codice:import java.io.*; import java.util.*; public class ListDir implements Comparator { public static void main(String args[]) throws FileNotFoundException { File dir = new File("/Volumes/MATTE/Dir"); String lista = ListDir.sortList(dir); System.out.println(lista); } public static List<File> listingDir(File dir) { List<File> file = new ArrayList<File>(); File[] elementi = dir.listFiles(); for (File files : elementi) { file.add(files); if (files.isDirectory()) { List<File> otherDir = listingDir(files); file.addAll(otherDir); } } return file; } public static String sortList(File dir) throws FileNotFoundException { validateDir(dir); List<File> file = listingDir(dir); String result = ""; Collections.sort(file); for (File files : file) { result += files.getAbsolutePath() + "\n"; } return result; } private static void validateDir(File dir) throws FileNotFoundException { if (dir == null) { throw new IllegalArgumentException("Directory should not be null."); } if (!dir.exists()) { throw new FileNotFoundException("Directory does not exist: " + dir); } if (!dir.isDirectory()) { throw new IllegalArgumentException("Is not a directory: " + dir); } if (!dir.canRead()) { throw new IllegalArgumentException("Directory cannot be read: " + dir); } } }
ho visto un pò in giro l'uso di compare.
ad esempio (dovrebbe ordinare dei numeri ma nn è il mio caso, lo prendo solo come esempio):
ho alcuni problemi.codice:public int compare(Object obj1, Object obj2) { ListDir c1 = (ListDir) obj1; ListDir c2 = (ListDir) obj2; int s1 = c1.getA() + c1.getB(); int s2 = c2.getA() + c2.getB(); return s1 - s2; }
innanzitutto mi conviene usare compare sul metodo listingDir che ritorna una List<File> o su sortDir che ritorna una String?
io ho pensato fosse meglio su sortDir in quanto andrei a sotituire Collections.sort().
e poi come vado a sostituire gli int con le String?