简体   繁体   中英

Problem with implementing Comparable interface

I have below codes that I implement form chapter 9 in book "Java for Everyone":

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. I already provided the compareTo method in the BankAccount class, why does it not work?

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)

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 . Instead use the core Java Comparable interface.

The issue here is that the Arrays.sort(...) method must use the core interface and not your own. 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:

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. Not the one you have created.

Remove below code from your BankAccount class. This will work.

interface Comparable{
int compareTo(Object otherObject);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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