【发布时间】:2018-11-29 06:23:57
【问题描述】:
下面提供的代码用于对int 值进行排序。我现在要做的,是将它们分类成Strings。
public class Comparable5 {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Student1(2, "Thilan"));
ts.add(new Student1(1, "Kamal"));
ts.add(new Student1(3, "Nimal"));
System.out.println(ts);
}
}
class Student1 implements Comparable<Student> {
int id;
String name;
public Student1(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return this.id + ":" + this.name;
}
@Override
public int compareTo(Student o) {
if (o.name.equals(this.name)) {
return -1;
} else if (o.name.equals(this.name)) {
return +1;
} else {
return 0;
}
}
}
我正在尝试使用 Comparable 接口提升名称。我使用了equals() 方法,但是我无法获得升序。我尝试使用可比较的界面比较不同的对象。我使用了一个有两个参数的构造函数。
我已经对 ID 进行了排序,但无法按名称(字符串)对它们进行排序。如何在 Comparable 接口中使用compareTo() 方法对字符串进行排序?
【问题讨论】:
-
最好先阅读class java doc
-
你为什么不做
o.name.compareTo? -
感谢您的帮助。我已经找到了办法。我们可以。是的,我们可以使用 override compareTo()。
标签: java sorting collections comparable