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
Discussions

Help with overriding compareTo()
Derek Derek is having issues with: Hello, I am trying to override compareTo() by lastNames (String). However, for some reason, I can't get it to work and keep getting Null... More on teamtreehouse.com
🌐 teamtreehouse.com
2
April 21, 2016
comparison - Tricky compareTo, inheritance, easy to extend - Java - Software Engineering Stack Exchange
I think what you want is sort of ... in Java using the Visitor-Pattern but you would have to change the code when adding new classes. Since you don't really need full-blown multiple dispatch I think the following might be a good solution. Write your compareTo methods like this: (This is the one in TestB) @Override public int ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 3, 2013
How to override compare method in Comparator
For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you · I'm stuck to override compare method in Comparator for ascending order sorting More on forums.oracle.com
🌐 forums.oracle.com
July 13, 2018
should i override the compareTo() method?
Only if you have extra fields and it these extra fields affect results of comparison. More on reddit.com
🌐 r/AskProgramming
8
0
July 24, 2022
🌐
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.

🌐
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 ...reTo(other.name); } } By implementing the compareTo() method, you can define the natural ordering of your custom objects, which is essential for using them in various Java collections and ...
🌐
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.
Find elsewhere
🌐
Oracle
forums.oracle.com › ords › apexds › post › how-to-override-compare-method-in-comparator-4651
How to override compare method in Comparator
July 13, 2018 - I'm stuck to override compare method in Comparator for ascending order sorting.I want to sort in ascending order of roll numberCode:class Sortbyroll implements Comparator { public i...
🌐
Coderanch
coderanch.com › t › 519975 › java › overriding-compareTo
overriding compareTo() (Java in General forum at Coderanch)
December 9, 2010 - 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.
🌐
Coderanch
coderanch.com › t › 696129 › java › overriding-compareTo-compare-integers
overriding compareTo to compare integers (Beginning Java forum at Coderanch)
July 2, 2018 - https://javarevisited.blogspot.com/2011/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. compareTo returns one of: zero (they are equal), a positive ...
🌐
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 are ...
🌐
Reddit
reddit.com › r/askprogramming › should i override the compareto() method?
r/AskProgramming on Reddit: should i override the compareTo() method?
July 24, 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).
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparable-interface-in-java-with-examples
Java Comparable Interface - GeeksforGeeks
It contains the compareTo() method, which compares the current object with another object. It is commonly used with Collections.sort() and Arrays.sort() for sorting custom objects.
Published   1 month ago
🌐
Zero To Mastery
zerotomastery.io › blog › java-compareto-method
Beginner's Guide To compareto In Java (With Code Examples) | Zero To Mastery
March 3, 2025 - Master Java’s compareTo method in minutes! Learn how to compare objects, avoid common mistakes, and write cleaner code with hands-on examples.
🌐
Xperti
xperti.io › home › a guide to implementing the java compareto method
A Guide to Implementing the Java CompareTo Method - Xperti
December 7, 2023 - In this guide, we will help you learn with practical examples how to implement the Java compareTo method and why and when to use it.
🌐
Codecademy
codecademy.com › docs › java › comparable
Java | Comparable | Codecademy
April 29, 2025 - By implementing this interface, a class indicates that its instances can be ordered or sorted. When a class implements the Comparable interface, it must override the compareTo() method to define the comparison logic between objects.
🌐
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().
🌐
Scaler
scaler.com › home › topics › java string compareto() method
Java String compareTo() Method with Examples - Scaler Topics
May 10, 2023 - The above class Book, implements the Comparable interface and overrides the compareTo() method. Book has three parameters, book_name, author, and year (year of book publication). Constructor method takes these three parameters to create an instance of Book class. In the main method, we create three Book objects namely, Java, Kotlin, and Python and we specify its parameters.
🌐
Igor's Techno Club
igorstechnoclub.com › java-compareto
Java Comparable compareTo method: Natural Order Of Things | Igor's Techno Club
July 22, 2024 - 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.