Search Results

Search found 1 results on 1 pages for 'user2677383'.

Page 1/1 | 1 

  • File sorting, Comparison method violates its general contract

    - by user2677383
    My file sorting comparator sometimes invoke java.lang.IllegalArgumentException in android app. I cannot figure out the reason. could you explain that? here is my code block: Comparator cc = new Comparator<File>() { @Override public int compare(File f1, File f2) { if (f1.isDirectory() && !f2.isDirectory()) { return 1; } if (f2.isDirectory() && !f1.isDirectory()) { return -1; } if ((f1.isFile() && f2.isFile()) || (f1.isDirectory() && f2.isDirectory())) { if (sort == 1) { return Util.compareFileName(f2.getName(), f1.getName()); } else if (sort == 2) { return (int) (f1.lastModified() - f2.lastModified()); } else if (sort == 3) { return (int) (f2.lastModified() - f1.lastModified()); } else if (sort == 4) { return (int) (f1.length() - f2.length()); } else if (sort == 5) { return (int) (f2.length() - f1.length()); } else return Util.compareFileName(f1.getName(), f2.getName()); } return f1.compareTo(f2); } }; Util.compareFileName is as followings: public static int compareFileName(String s1, String s2) { int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }

    Read the article

1