简体   繁体   中英

Which method do I have to overwrite in Java to use “>” to compare instances of my class

As far as I understand I can overwrite equals() in Java to handle how my class interacts with == . Which method do I have to overwrite to be define the behavior of

MyClass obj1;
MyClass obj2;
if (obj1 > obj2){
    ...
}

You can't. Java doesn't support custom operator overloading. Overriding equals doesn't affect == . The closest you can get to < is to implement the Comparable interface, which includes a compareTo method. http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

As far as I understand I can overwrite equals() in Java to handle how my class interacts with ==

This is wrong. The explanation is already covered here: How do I compare strings in Java? :

== tests for reference equality.

.equals() tests for value equality.


To your question:

Unlike C++ or C#, in Java you cannot overload operators.

Instead of using > and < operators you have two options.

  1. Make MyClass implement Comparable :

     public MyClass implements Comparable<MyClass> { @Override public int compareTo(MyClass other) { //comparison logic here... } } 

    You will use it like this:

     MyClass obj1 = ...; MyClass obj2 = ...; if (obj1.compareTo(obj2) > 0){ ... } 
  2. Create a class that implements Comparator

     public class MyClassComparator implements Comparator<MyClass> { @Override public int compare(MyClass myClass1, MyClass myClass2) { //comparison logic here... } } 

    You will use it like this:

     MyClass obj1 = ...; MyClass obj2 = ...; MyClassComparator comp = new MyClassComparator(); if (comp.compare(obj1, obj2) > 0){ ... } 

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