gpt4 book ai didi

java - 如何在Java中正确使用Comparable来处理字符串?

转载 作者:行者123 更新时间:2023-12-01 08:45:37 25 4
gpt4 key购买 nike

我有以下界面:

public interface Generator <T> {
public T next ();}

以及具有多个方法和字段的类。我将按顺序编写代码,以便您能够理解我的问题。类(class):

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 :(

}

我对我的英语感到抱歉。英语不是我的母语。谢谢:)

最佳答案

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 

关于java - 如何在Java中正确使用Comparable来处理字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com