无法在Java中@Override compareTo()方法 [英] Unable to @Override the compareTo() method in Java

查看:120
本文介绍了无法在Java中@Override compareTo()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个 BankAccount 类,它将一堆银行账户放入一个数组列表中,并根据他们的账号对它们进行排序。我写了 compareTo()方法,如下所示:

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. I wrote the compareTo() method as follows:

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;

在我的主要方法中, accounts 是数组列表的变量。当我尝试 Collections.sort(accounts); 时,它无法执行此操作。它给我一个错误,说不能从参数实例化,因为实际和形式参数的长度不同和推断类型不符合声明的约束。我认为这是因为我没有覆盖 compareTo()方法但是当我尝试 @Override它时,它说方法不会覆盖或实现超类型的方法。我不明白问题是什么。任何帮助将不胜感激。

In my main method, accounts is the variable for the array list. When I try to do 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". I don't understand what the problem is. Any help would be appreciated.

推荐答案

您的 BankAccount 类应该实现 java.lang.Comparable< BankAccount> 界面,您的代码中似乎不是这种情况。的确, Collection.sort Comparable< T> 的集合作为参数。

Your BankAccount class should implement the java.lang.Comparable<BankAccount> interface, it appears this is not the case in your code. Indeed, Collection.sort is taking a collection of Comparable<T> as an argument.

这篇关于无法在Java中@Override compareTo()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆