日期:2014-05-20 浏览次数:20796 次
import java.util.*; class Chara implements Comparable{ String s; Chara(String s){ this.s = s; } public boolean equals(Object o){ Chara c = (Chara)o; return s.equals(c.s); } public int hashCode(){ int result = 31; int c = s.length(); result = 37* result + c; return result; } public int compareTo(Object o){ Chara c = (Chara)o; int r =0; char ch1 = s.charAt(0); char ch2 = c.s.charAt(0); r = Character.toLowerCase(ch1) - Character.toLowerCase(ch2); if(r != 0){ return r; }else{ return ch2 - ch1 ; } } public String toString(){ return s; } } public class aAbB { public static void main(String[] args) { List cc = new LinkedList(); cc.add(new Chara("D")); cc.add(new Chara("d")); cc.add(new Chara("Bank")); cc.add(new Chara("chair")); cc.add(new Chara("apple")); cc.add(new Chara("Chat")); cc.add(new Chara("Andriod")); cc.add(new Chara("Egg")); cc.add(new Chara("bannana")); Collections.sort(cc); System.out.println(cc); } }
------解决方案--------------------
java.lang.String
public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;
int n = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
} else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
if (c1 != c2) {
return c1 - c2;
}
}
}
return len1 - len2;
}
自己修改下。