user9043248
user9043248

Reputation:

CompareTo Method

I finally think I found a way to sort my transactions by amount using the if statement but I need a way to indicate when one transaction is less or greater than the other they exchange places.

I have a sample of what I've done so far and not too sure what I am missing out here.

    @Override
public int compareTo(Student_Transaction Tra)
{    
    if (getAmount() == ((Student_Transaction) Tra).getAmount()) {
        return Amount - Tra.getAmount();
    }
    else if (getAmount() > ((Student_Transaction) Tra).getAmount()) { 
        return 1;
    }
    else if (getAmount() < ((Student_Transaction) Tra).getAmount()) {
        return -1;
    }
    return Amount;
}

Upvotes: 0

Views: 113

Answers (3)

user9043248
user9043248

Reputation:

I literally realised that what I did in the thread above was the answer to my question, it clearly defined how I will sort my amounts in each transaction object the final fold of this stage was to use the collection.sort method and in one of the recent threads I have posted the answer to how it is done...

@Override
public int compareTo(Student_Transaction Tra){
    if (Tra.getAmount() < getAmount()) { 
        return -1; 
    }
    else if (Tra.getAmount() == getAmount()) { 
        return 0;
    }
    else {
        return 1; // Tra.getAmount() > getAmount()
    }
}

I didn't need to go the extra mile, ya boy just is misunderstood with his programming and I'm much appreciated with have this community of professional programmers dedicating their time to help people like me out :)

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18253

This is compareTo method of Student_Stransaction, so no need to use getters:

@Override
public int compareTo(Student_Transaction Tra) {
    return Tra != null ? Float.compare(amount, Tra.amount)) : 1;
}

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56489

I'd suggest you go with:

return Double.compare(this.amount, tra.getAmount());

which means, you can avoid having to do all those if/else if conditions.

Upvotes: 0

Related Questions