[英]Unable to @Override the compareTo() method in Java
I'm writing a BankAccount
class that puts a bunch of bank accounts into an array list and sorts them according to their account number. 我正在写一个
BankAccount
类,它将一堆银行账户放入一个数组列表中,并根据他们的账号对它们进行排序。 I wrote the compareTo()
method as follows: 我写了
compareTo()
方法如下:
public int compareTo(BankAccount another){
if (Integer.parseInt(this.getAccountNumber()) > Integer.parseInt(another.getAccountNumber()))
return 1;
else if(Integer.parseInt(this.getAccountNumber()) < Integer.parseInt(another.getAccountNumber()))
return -1;
else
return 0;
In my main method, accounts
is the variable for the array list. 在我的main方法中,
accounts
是数组列表的变量。 When I try to do Collections.sort(accounts);
当我尝试做
Collections.sort(accounts);
it is unable to do it. 它无法做到。 It gives me an error saying something like "cannot instantiate from arguments because actual and formal arguments differ in length" and "inferred type does not conform to declared bound(s)".
它给我一个错误,说“不能从参数实例化,因为实际和形式参数的长度不同”和“推断类型不符合声明的约束”。 I thought this was due to my not overriding the
compareTo()
method but when I try to @Override it
, it says "method does not override or implement a method from a supertype". 我认为这是因为我没有覆盖
compareTo()
方法,但当我尝试@Override it
,它说“方法不会覆盖或实现超类型的方法”。 I don't understand what the problem is. 我不明白问题是什么。 Any help would be appreciated.
任何帮助,将不胜感激。
Your BankAccount
class should implement the java.lang.Comparable<BankAccount>
interface, it appears this is not the case in your code. 您的
BankAccount
类应该实现java.lang.Comparable<BankAccount>
接口,看起来在您的代码中不是这种情况。 Indeed, Collection.sort
is taking a collection of Comparable<T>
as an argument. 实际上,
Collection.sort
正在将Comparable<T>
的集合作为参数。
确保您的类声明如下所示:
public class BankAccount implements Comparable<BankAccount>
In order to Override the compareTo
method your class has to implement the Comparable
interface. 为了覆盖
compareTo
方法,您的类必须实现Comparable
接口。 compareTo
is not, by default, part of java.lang.Object
. compareTo
默认情况下不是java.lang.Object
一部分。
Sounds like you forgot to have your class implement Comparable. 听起来你忘了让你的班级实现可比较。 Make sure your class declaration looks like this:
确保您的类声明如下所示:
... class BankAccount ... implements Comparable<BankAccount>
Does your class implement the Comparable interface? 你的类是否实现了Comparable接口? If yes can you check the import to make sure it is the default (java.lang.Comparable) instead of from some other package
如果是,您可以检查导入以确保它是默认值(java.lang.Comparable)而不是其他包
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.