要按照aAbB。。。这种字母顺序排序应该如何实现啊?
求教。
------解决方案--------------------
------解决方案--------------------
3楼的实现挺好的啊 else后面就是同个字母判断大小写的功能
我也是初学者,刚写的用容器来排序
本来判断大小的代码有点繁琐,上面的方法挺好的,就学来了。呵呵
- Java code
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;
}
自己修改下。