As I see you have wrong implementation of compare method. Could you update it to?

@Override
public int compareTo(User user) {
  return Integer.compare(age, user.age);
}
Answer from Roma Khomyshyn on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-override-compareto-method-in-java
How to Override compareTo() Method in Java? - GeeksforGeeks
July 23, 2025 - Since we have overridden the compareTo() method, so objects will be compared by using this compareTo() methods, based on the age. ... // Java Program to show how to override the compareTo() method of Comparable interface import java.util.*; // Class implementing Comparable interface public class GFG implements Comparable<GFG> { String name; // Name of the person int age; // Age of the person // Class constructor GFG(String name, int age) { this.name = name; this.age = age; } // Getter for age public int getAge() { return age; } // Getter for name public String getName() { return name; } public
🌐
Blogger
javarevisited.blogspot.com › 2011 › 11 › how-to-override-compareto-method-in.html
How to override compareTo method in Java - Example Tutorial
Let’s see an example of how to override compareTo method in Java. This method is very similar to equals and hashcode, key thing is compareTo should provide natural ordering e.g.
🌐
LabEx
labex.io › tutorials › java-how-to-override-compareto-method-in-a-java-class-414097
How to override compareTo() method in a Java class | LabEx
@Override public int compareTo(Person other) { if (this.age < other.age) { return -1; } else if (this.age > other.age) { return 1; } else { return this.name.compareTo(other.name); } } By implementing the compareTo() method, you can define the ...
🌐
Reddit
reddit.com › r/javahelp › my compareto method is seemingly not overriding?
r/javahelp on Reddit: My compareTo method is seemingly not overriding?
March 4, 2021 -

Hello my good people, this is my first Java program ever and I ran into an issue I don't know how to fix, even after a bunch of research. So I'm trying to override the compareTo method, so I can sort a list of objects by name, but when I put that list into Collections.sort, it shows an error saying "no instance(s) of type variable(s) T exist so that MyClass conforms to Comparable<? super T>" Here's the relevant code, I can post more if you want:

Comparable interface:

 public interface Comparable<Jed> {
     int compareTo(Jed jed);
 }

Class Jed, that implements Comparable:

public class Jed implements Comparable<Jed> {
    String ime;
    
    @Override
    public int compareTo(Jed jed){
        return this.ime.compareTo(jed.getIme());
    }
}

The class which holds the list that I want sorted:

public class Racun {
    private List<Jed> seznamJedi;
    
    public void sort(){
        Collections.sort(seznamJedi);
    }    

I hope I didn't miss anything relevant, but yeah, any help would be greatly appreciated and maybe an explanation on why this is happening.

🌐
Delft Stack
delftstack.com › home › howto › java › override compareto method in java
How to Override the CompareTo Method in Java | Delft Stack
February 2, 2024 - Let’s see another example of the compareTo() method to compare the ages of two objects. package java example; import java.util.*; public class SimpleTesting implements Comparable<SimpleTesting> { // Java Program which shows how to override the compareTo() method of comparable // interface // implementing Comparable interface int age; // Creating constructor SimpleTesting(int age) { this.age = age; } public static void main(String[] args) { // Creating a dynamic array by using an arraylist List<SimpleTesting> list = new ArrayList<>(); // Inserting elements in the objects list.add(new SimpleTesting(56)); list.add(new SimpleTesting(66)); list.add(new SimpleTesting(21)); Collections.sort(list); list.forEach(el -> System.out.println(el.age)); } // Overriding compareTo() method @Override public int compareTo(SimpleTesting user) { return this.age >= user.age ?
🌐
Coderanch
coderanch.com › t › 696129 › java › overriding-compareTo-compare-integers
overriding compareTo to compare integers (Beginning Java forum at Coderanch)
It's easiest to just use ...1/11/how-to-override-compareto-method-in.html CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario....
Find elsewhere
🌐
Java67
java67.com › 2013 › 04 › example-of-overriding-equals-hashcode-compareTo-java-method.html
How to Override Equals, HashCode and CompareTo method in Java | Java67
Anyway, here is a simple example of overriding equals, hashcode and compareTo in Java. In this sample example of overriding equals, hashcode and compareTo method, we will use a class named Person which has 3 properties String name, int id and Date to represent date of birth.
🌐
Quora
quora.com › Why-do-we-need-to-override-compare-to-the-method-or-implement-comparable-in-Java-and-why-does-it-need-to-be-consistent-with-equals
Why do we need to override compare to the method or implement comparable in Java, and why does it need to be consistent with equals? - Quora
Answer (1 of 4): Perhaps the best way to answer this question is to quote from one of the answers given at Implementing equals method using compareTo where: “The difference between [code ]equals()[/code] and [code ]compareTo()[/code] is that [code ]equals()[/code] just checks if two objects ...
🌐
Igor's Techno Club
igorstechnoclub.com › java-compareto
Java Comparable compareTo method: Natural Order Of Things | Igor's Techno Club
The compareTo method is a fundamental tool in Java for establishing order among objects. By implementing the Comparable interface and overriding compareTo, you can define custom ordering for your classes, enabling them to be easily sorted and compared.
🌐
Coderanch
coderanch.com › t › 519975 › java › overriding-compareTo
overriding compareTo() (Java in General forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... The compareTo method of the Comparable interface returns an integer.
🌐
Baeldung
baeldung.com › home › java › core java › guide to implementing the compareto method
Guide to Implementing the compareTo Method - Java
May 29, 2025 - TreeMap and TreeSet are two implementations from the Java Collections Framework that assist us with the automatic sorting of their elements. We may use objects that implement the Comparable interface in a sorted map or as elements in a sorted set. Let’s look at an example of a custom class that compares players based on the number of goals they have scored: @Override public int compareTo(FootballPlayer anotherPlayer) { return Integer.compare(this.goalsScored, anotherPlayer.goalsScored); }
🌐
Reddit
reddit.com › r/askprogramming › should i override the compareto() method?
r/AskProgramming on Reddit: should i override the compareTo() method?
July 23, 2022 -

i don't know if i should write it as compareTO(Object UNP) or compareTo(RentalCars UNP) also am i using the equals() method correctly or am i missing something?

/*
Class Car(implements the interface: Comparable<> )
- Attributes:
o Unique number plate (final) : String
o Brand: String
o Rental rate: double
o Extra three (from your choice)
- Methods:
o Constructors: zero-arg and multi-arg
o getters
o setters (if needed)
o toString()
o equals(): compare plate numbers
o compareTo(): compare plate numbers
 */
import java.io.*;
import java.util.*;
// i know i should change it from Rentalcars to RentalCar
public class RentalCars implements Comparable<RentalCars> {
//UNP is the unique plat numbers
  final String UNP;
  private String brandName;
  private double rentalRates;
  private int wheelDrive;
  private String color;
  private int milage;
  
  
  
public RentalCars(){
      this(null,null, 0.0, 0, null, 0);
  }
public RentalCars(String UNP, String brandName, double rentalRates, int wheelDrive,
   String color, int milage){
    
      this.UNP = UNP;
      this.brandName=brandName;
      this.rentalRates=rental_Rates;
      this.wheelDrive=wheel_Drive;
      this.color=color;
      this.milage=milage;
  }
public String getUNP() {
    return UNP;
    }
public String getbrandName() {
     return brandName;
    }
public void setbrandname(String brandName) {
    this.brandName=brandName;
    }
public double getrentalRates() {
    return rentalRates;
    }
public void setrental_Rates(double rentalRates) {
    this.rentalRates=rentalRates; 
    } 
public int getwheelDrive() {
    return wheelDrive;
    }
public void setwheel_Drive(int wheelDrive) {
    this.wheelDrive=wheelDrive; 
    }
public String getcolor() {
    return color;
    }
public void setcolor(String color) {
    this.color=color; 
    }
public int getmilage() {
    return milage;
    }
public void setmilage(int milage) {
    this.milage=milage; 
    }

@Override
public String toString()
{
    return "the Number Plate of the car is "+UNP+"the Car brand is "+brandName+
            "the rent rate of this car is "+rental_Rates+"the wheel drive is "+
            wheel_Drive+"the color of the car is "+color+"the milage is "+milage;
 }
public boolean equals(RentalCars obj){
    RentalCars rc = (RentalCars) obj;
    if(UNP != rc.UNP)
        return false;
    
    return true;
 }
  public int compareTo(RentalCars UNP){
  
  }
}
Top answer
1 of 2
2
Only if you have extra fields and it these extra fields affect results of comparison.
2 of 2
2
I don't think the JavaScript tag is correct here. This is a Java question. Despite the unfortunately similar names, they are completely different languages. You're probably using equals wrong. There are two issues: You haven't matched the signature of Object.equals, so you've created a method overload (Java allows you to have multiple methods with the same name as long as they take different parameter types). If you intent to implement Object.equals, then you must also implement hashCode. So in Java, every class derives (directly or indirectly) from Object . That means that every class gets some handful of methods added to it automatically. One of those methods is equals(Object) . It has some default behavior, but the default is basically just a reference check. Unless a class Foo provides a custom implementation, someFoo.equals(someOtherFoo) is basically the same as someFoo == someOtherFoo. You've created your own equals method, but it is equals(RentalCars), not equals(Object). As a result, you've added a different equals method to your class. Essentially, your class looks like this: class RentalCars { //... public boolean equals(Object obj) { return this == obj; } public boolean equals(RentalCars obj) { RentalCars rc = (RentalCars) obj; //this cast does nothing if(UNP != rc.UNP) return false; return true; } //... } Well if there are two equals methods, which one gets called? It depends on the callsite: RentalCars rc1 = new RentalCars(); RentalCars rc2 = new RentalCars(); rc1.equals(rc2); // calls equals(RentalCars) Object obj2 = rc2; rc1.equals(obj2); // calls equals(Object) For this reason, it's dangerous to create method overloads like this when the two methods behave differently. So I'm going to assume that you were trying to implement equals(Object). You need to change your method to have that signature, and you should consider adding an @Override annotation to that method: @Override public boolean equals(Object obj) { ... } If you get the signature wrong, the compiler will complain. I don't remember off the top of my head if the compiler produces an error or a warning. As mentioned in this comment on your other post , if you implement equals, you must also implement hashCode. If equals checks whether two objects are, well, equal, then hashCode checks if they're "almost equal". The idea behind a hash code is that equal objects will return the same hash code. Unequal objects would ideally return wildly different hash codes, but since the hash code is just an int, there will be collisions and that's OK. The important thing is that IF equals returns true for two objects, THEN those two objects must have the same hash code. On the other hand, IF two objects return the same hash code, THEN they may or may not be equal to each other. Like I said, it's a "roughly equals" check. This combination of hashCode / equals is used for containers like HashSet and HashMap. If they're not compatible then your type won't work correctly with these collections. If you implement Comparable, then you want to have a method int compareTo(RentalCars rc). Again, you can use @Override to help ensure you get it right. You can determine the correct signature by looking at the definition of the method in the interface . You see that the parameter has type T, which must be the same type as appears between the angle brackets. So if you have Comparable, then your method should be compareTo(Foo).
🌐
Coderanch
coderanch.com › t › 441985 › java › Comparable-override-compareTo
Comparable - must override compareTo()??? (Java in General forum at Coderanch)
For example, ScheduledFuture extends Delay, which again extends Comparable<Delay>. So ScheduledFuture is not a Comparable<ScheduledFuture>, but a Comparable<Delay>, and the "? super T" will make sure that ScheduledFuture will also be a match for T. Well, I'll be darned, now I don't have to cast to Comparable<T> any more! OK, so, just to make sure I understand this: 'T extends Comparable' will make sure that any T must have its own version of compareTo().
🌐
Medium
medium.com › omarelgabrys-blog › comparing-objects-307400115f88
Comparing Objects. Add the Comparable flavor, and taste… | by Omar Elgabry | OmarElgabry's Blog | Medium
December 26, 2021 - In your sorting method, it should take an argument of Comparable array type, and it will trigger compareTo method on each object in the array.
🌐
Tutorialspoint
tutorialspoint.com › home › java › java comparator example
Java Comparator Example
September 1, 2008 - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Dog implements Comparator<Dog>, Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } // Overriding the compare method to sort the age public int compare(Dog d, Dog d1) { return d.age - d1.age; } @Override public String toString() { return