public class Sorting {
Vector<Talk> sorty(Vector <Talk> s) {
Collections.sort(s);
return s;
}
}
我需要对类Talk
的对象进行排序,但我一直得到错误
&#34;绑定不匹配&#34;。
Talk Class就是这样的:
public class Talk {
String name;
int duration;
public int compareTo(Talk t) {
int compare = t.duration;
return this.duration - compare;
}
}
答案 0 :(得分:3)
如果要对包含它的列表进行排序,您的Talk
类需要实现Comparable
接口:
public class Talk implements Comparable<Talk> {
请注意,通过相互减去int
值进行比较是不安全的,除非您知道这两个值仅为正值(或者不超过Integer.MAX_VALUE
值)精确)。原因是int
会溢出并且如果值比那些值更大则错误地转为负值。不会发生很多事情,但如果确实发生这种情况就很难追查,所以最好让自己习惯于另类。
一种更好的比较方法,就是调用Integer.compare(int, int)
:
public int compareTo(Talk t) {
return Integer.compare(duration, t.duration);
}
答案 1 :(得分:1)
Talk确实实现了compareTo
方法,但它没有实现Comparable
接口,这是compareTo应该被覆盖的地方。
将您的谈话更改为:
public class Talk implements Comparable{
String name;
int duration ;
@Override
public int compareTo(Object o)
{ Talk t = (Talk)o;
int compare = t.duration;
return this.duration - compare;
}
}
对我来说,我总是喜欢固定的-1,0或1回报:
@Override
public int compareTo(Object o)
{ Talk t = (Talk)o;
int compare = t.duration;
return this.duration == compare ? 0 : this duration > compare ? 1 : -1;
}
但这不是强制性的。
但是,我会建议重新考虑变量的访问修饰符。通常,建议使用私有变量而不是包可见性。答案 2 :(得分:0)
我希望我能帮助你。
public class TestSorting {
/**
* @Desc:
*
* @param args
*
* @Author: luochao
* @CreateTime: 2016年2月3日
*/
public static void main(String[] args) {
Vector<Talk> vector = new Vector<Talk>();
vector.add(new Talk("centos",3));
vector.add(new Talk("linux",1));
vector.add(new Talk("java",2));
}
}
class Talk implements Comparable<Talk> {
private String name;
private int duration;
public Talk(String name,int duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
@Override
public int compareTo(Talk o) {
int compare = o.duration;
return -(this.duration - compare);
}
}