我有以下界面:
public interface Generator <T> {
public T next ();}
以及具有多个方法和字段的类。我会按顺序编写代码,这样你就能理解我的探索。 类:
public class Example implements Comparable <Example>{}
此类包含以下字段:
private String name;
private static int count;
private int ID = count ++;
private static char [] chars = "qwertyuiopasdfghjklzxcvbnm".toCharArray();
构造
public Example (String name){
this.name = name;
}
返回有关类的信息的方法:
public String toString (){
return "ID #" + ID + ", name: " + name;
}
产生新类的方法:
public static Generator <Example> generator (){
return new Generator <Example> (){
public Example next() {
Random rand = new Random ();
StringBuilder str = new StringBuilder ();
for (int i=0; i!=10; i++)
str.append(chars[rand.nextInt(chars.length)]);
return new Example (str.toString());
}
};
}
这个我无法理解的难以理解的方法:
public int compareTo(Example o) {
return (this.name < o.name ? -1 : (this.name == o.name ? 0 : 1)); // It does not works... :(
}
生成数组的通用方法:
public static <T> List <T> array (List <T> list, Generator <T> gen, int size){
for (int i=0; i!=size; i++){
list.add(gen.next());
} return list;
}
和我尝试比较排序数组时的主要方法:
public static void main (String [] args){
List <Example> list = new ArrayList <Example> (); // Created the array;
array (list, generator(), 10); // Filled the array;
Collections.sort(list); // Doesn't work :(
}
对不起我的英语。英语不是我的母语。 谢谢:))
答案 0 :(得分:1)
return (this.name < o.name ? -1 : (this.name == o.name ? 0 : 1)); // It does not works... :(
在您的compareTo()
实现中,您正在将String与<
运算符进行比较,该运算符无效。你可以像
return this.name.compareTo(o.name); // for natural string comparison