Java实现集合,文件,数组排序 - 编程入门网
使用Comparator对文件实现了按文件大小或修改时间排序:
class FileUtils { static class CompratorByLastModified implements Comparator { public int compare(Object o1, Object o2) { File file1 = (File)o1; File file2 = (File)o2; long diff = file1.lastModified() - file2.lastModified(); if (diff > 0) return 1; else if (diff == 0) return 0; else return -1; } public boolean equals(Object obj){ return true; //简单做法 } } static class CompratorBySize implements Comparator { public int compare(Object o1, Object o2) { File file1 = (File)o1; File file2 = (File)o2; long diff = file1.length() - file2.length(); if (diff > 0) return 1; else if (diff == 0) return 0; else return -1; } public boolean equals(Object obj){ return true; //简单做法 } } } Java实现集合,文件,数组排序(3)时间:2011-06-19 ITeye mx19841031调用的示例: File dir = new File("C:\\temp"); File[] files = dir.listFiles(); System.out.print("before sort: "); for (int i = 0; i< files.length; i++) System.out.print(files[i] + " "); System.out.println(); Arrays.sort(files); System.out.print("sort by name: "); for (int i = 0; i< files.length; i++) System.out.print(files[i] + " "); System.out.println(); Arrays.sort(files, new FileUtils.CompratorBySize()); System.out.print("sort by size: "); for (int i = 0; i< files.length; i++) System.out.print(files[i] + " "); System.out.println(); Arrays.sort(files, new FileUtils.CompratorByLastModified()); System.out.print("sort by last modified: "); for (int i = 0; i< files.length; i++) System.out.print(files[i] + " "); System.out.println(); 自己找个目录试一下吧。用这些Java类库中的方法,一般情况下应该是不用自己写排序算法了吧? 最后附上完整代码占点版面: import java.io.*; import java.util.*; public class TestSort { public static void main(String[] args) { sortSimpleType(); sortComparable(); sortComparator(); } public static void sortSimpleType() { int[] arr = {2, 3, 1,10,7,4}; System.out.print("before sort: "); for (int i = 0; i< arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); Arrays.sort(arr); System.out.print("after sort: "); for (int i = 0; i< arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); } public static void sortComparable() { ArrayList list = new ArrayList(); list.add(new Programmer("张三", "C", 12000)); list.add(new Programmer("李四", "Java", 200)); list.add(new Programmer("王五", "C++", 5000)); list.add(new Programmer("钱六", "VB", 3000)); System.out.println("before sort: " + list); Collections.sort(list); System.out.println("after sort: " + list); } public static void sortComparator() { File dir = new File("C:\\java"); File[] files = dir.listFiles(); System.out.print("before sort: "); for (int i = 0; i< files.length; i++) System.out |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |