有问题的代码如下:
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
public class Test{
public static void main(String[] args) {
List<Human> humans= newArrayList<Human>();
humans.add(newHuman(13));
humans.add(newHuman(33));
humans.add(newHuman(21));
humans.add(newHuman(21));
Collections.sort(humans);
System.out.print(humans.get(0).age);
System.out.print(humans.size());
}
}
class Human implements Comparable<Human> {
int age;
public Human(int age) {
this.age = age;
}
public int compareTo(Human h) {
return h.age.compareTo(this.age);
}
}
我想知道为什么这段代码会导致编译错误?我不确定我要去哪里。
一些额外的细节:
答案 0 :(得分:1)
诸如shrot,int,long,double之类的原始类型未实现Comparable接口。使您的实例变量成为对象类型。在创建新对象(new Human(13))的同时,导入也会发生变化。
as_str = [str (y) for y in target_ls]
final_str = "\t".join(as_str) + "\n"
答案 1 :(得分:0)
您会错过代码中的许多空格。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test{
public static void main(String[] args) {
List<Human> humans= new ArrayList<Human>();
humans.add(new Human(13));
humans.add(new Human(33));
humans.add(new Human(21));
humans.add(new Human(21));
Collections.sort(humans);
System.out.print(humans.get(0).age);
System.out.print(humans.size());
}
}
class Human implements Comparable<Human> {
int age;
public Human(int age) {
this.age = age;
}
public int compareTo(Human h) {
return h.age - this.age;
}
}