import?java.util.Scanner;
//必須實現Comparable接口
public?class?Word?implements?Comparable<Word>{
private?final?String?word;
public?String?getWord()?{
return?word;
}
//構造器什麽的無視吧
public?Word(String?word)?{
if(word?==?null)
throw?new?NullPointerException("不可以創造空單詞!");
this.word?=?word;
}
//實現compareTo方法.主要的排序思路在這裏
@Override
public?int?compareTo(Word?target)?{
if(target?==?null)
return?1;
if(target.getWord().equalsIgnoreCase(getWord()))
return?0;
char[]?selfLetters?=?getWord().toLowerCase().toCharArray();
char[]?targetLetters?=?target.getWord().toLowerCase().toCharArray();
int?selfLength?=?selfLetters.length;
int?targeLength?=targetLetters.length;
int?minLength?=?Math.min(selfLength,?targeLength);
for(int?index?=?0;index?<?minLength;index++){
if(selfLetters[index]?>?targetLetters[index]){
return?1;
}
else?if?(selfLetters[index]?<?targetLetters[index]){
return?-1;
}
continue;
}
return?selfLength?>?targeLength1?:?-1?;
}
//重寫?ToString?方法以便打印輸出
@Override
public?String?toString()?{
return?word;
}
//主方法.用來查看效果
public?static?void?main(String[]?args)?{
?
int?size?=?5;//測試用的數組長度(單詞數);
//?創造壹個Word的數組用來保存輸入的單詞
Word[]?words?=?new?Word[size];
Scanner?sc?=?new?Scanner(System.in);
for(int?i=0;i<size;i++)
{
System.out.println("請輸入第"+(i+1)+"個單詞");
words[i]?=?new?Word(sc.nextLine());
}
sc.close();//關閉流
System.out.println("排序結果為:");
//使用Arrays.sort方法排序,sort對自動調用妳的compareTo方法來比較
Arrays.sort(words);
//打印出結果
System.out.println(Arrays.toString(words));
}
} 這是我剛寫的。測試結果還可以。邏輯可能不是很嚴謹 不過作為作業應該應付足夠了