简体   繁体   English

实现 Comparable 接口的问题

[英]Problem with implementing Comparable interface

I have below codes that I implement form chapter 9 in book "Java for Everyone":我有以下代码,我在“Java for Everyone”一书中实现了第 9 章:

package Inheritance;

import java.util.Scanner;

interface Comparable{
    int compareTo(Object otherObject);
}

interface Measurable{
    double getMeasure();
}


public class BankAccount implements Comparable, Measurable {
    private double balance;
    private int counter;
    public String account;

    public BankAccount(){
        balance = 0;
        counter = 0;
        account = "";
    }

    public void SetAccount(String accountNumber, double amount){
        account = accountNumber;
        balance = amount;
    }

    public void Deposit(double amount){
        balance = balance + amount;
        counter = counter + 1;
        System.out.println("Account: "+ account + " has balance: " + balance);
    }

    public void Withdraw(double amount){
        balance = balance - amount;
        counter = counter + 1;
        System.out.println("Account: "+ account + " has balance: " + balance);
    }

    public double getBalance(){
        return balance;
    }

    public void MonthEnd(){
        counter = 0;
    }

    public void printMenu(){
        System.out.println("Please choose your options to proceed: ");
        System.out.println("D)eposit W)ithdraw M)onth end Q)uit");
    }

    public double getMeasure(){
        return balance;
    }

    public int compareTo(Object otherObject) {
        BankAccount other = (BankAccount) otherObject;
        if (balance < other.balance) {
            return -1;
        }
        if (balance > other.balance) {
            return 1;
        }
        return 0;
    }

Then I run it as below:然后我运行它如下:

public class Implementation {

    public static void main(String[] args) {

        //Implement Comparable Interface example
        BankAccount[] accounts2 = new BankAccount[3];
        accounts2[0] = new BankAccount();
        accounts2[0].SetAccount("SA001", 10000);
        accounts2[1] = new BankAccount();
        accounts2[1].SetAccount("SA001", 5000);
        accounts2[2] = new BankAccount();
        accounts2[2].SetAccount("SA001", 20000);
        System.out.println(accounts2[0].compareTo(accounts2[1]));

        Arrays.sort(accounts2);
    }
}

However it gave me below error with my Comparable interface.但是,我的 Comparable 界面给了我以下错误。 I already provided the compareTo method in the BankAccount class, why does it not work?我已经在 BankAccount class 中提供了 compareTo 方法,为什么它不起作用?

Exception in thread "main" java.lang.ClassCastException: class Inheritance.BankAccount cannot be cast to class java.lang.Comparable (Inheritance.BankAccount is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320) Exception in thread "main" java.lang.ClassCastException: class Inheritance.BankAccount cannot be cast to class java.lang.Comparable (Inheritance.BankAccount is in unnamed module of loader 'app'; java.lang.Comparable is in module java. java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320) 的加载程序“引导程序”的基础

at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)

at java.base/java.util.Arrays.sort(Arrays.java:1250)

at Inheritance.Implementation.main(Implementation.jav

Get rid of:摆脱:

interface Comparable{
    int compareTo(Object otherObject);
}

Since you're confusing the compiler by creating your own interface that shadows the core Java interface of the same name .由于您通过创建自己的接口来混淆编译器,该接口隐藏了同名的核心 Java 接口。 Instead use the core Java Comparable interface.而是使用核心 Java 可比接口。

The issue here is that the Arrays.sort(...) method must use the core interface and not your own.这里的问题是Arrays.sort(...)方法必须使用核心接口,而不是你自己的。 Otherwise your code could possibly work although would likely confuse other coders and more importantly your future self .否则你的代码可能会工作,虽然可能会混淆其他编码人员,更重要的是你未来的自我

Side note, I would recommend using the generic version of the interface.旁注,我建议使用接口的通用版本。 I also like to always add the @Override annotation above any method that I think that I might be overriding so that the compiler will test this for me and warn me at compile time:我还喜欢总是在我认为我可能会覆盖的任何方法上方添加@Override注释,以便编译器会为我测试并在编译时警告我:

public class BankAccount implements Comparable<BankAccount>, Measurable {

    @Override
    public int compareTo(BankAccount other) {
        // ....
    }

To make work Arrays.sort(accounts2) function working, your BankAccount class has to implement the Comaparable interface provided by jdk itself - java.lang.Comparable. To make work Arrays.sort(accounts2) function working, your BankAccount class has to implement the Comaparable interface provided by jdk itself - java.lang.Comparable. Not the one you have created.不是你创建的那个。

Remove below code from your BankAccount class.从您的 BankAccount class 中删除以下代码。 This will work.这将起作用。

interface Comparable{
int compareTo(Object otherObject);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM