Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two instances of a class in Java

Tags:

java

I have a class with two integer members. These members are block and offset numbers. I need to compare two instances of this class with great or less signs. For example;

instance1 < instance2

statement needs to return true if

instance1.blockNumber < instance2.blockNumber;

or

instance1.blockNumber = instance2.blockNumber;
instance1.offset < instance2.offset;

As far as I know Java doesn't support operator overloading. How can I do this such comparison?

like image 625
Umut Derbentoğlu Avatar asked Apr 10 '26 01:04

Umut Derbentoğlu


2 Answers

Have the class implement the Comparable interface, which gives the compareTo method. You can then use the value of the number (-1 for less, 1 for more, 0 for equals) in your if statements.

If you want to put these objects in lists (say, for sorting) you should also @Override the .equals method.

import java.util.Comparable;

public class BlockOffset implements Comparable<BlockOffset>
{
  private int blockNumber;
  private int offset;

  @Override
  public int compareTo(BlockOffset instance2) {
    if (this.blockNumber < instance2.blockNumber) return -1;
    if (this.blockNumber > instance2.blockNumber) return 1;
    if (this.offset < instance2.offset) return -1;
    if (this.offset > instance2.offset) return 1;

    return 0;
  }   
}
like image 161
durron597 Avatar answered Apr 11 '26 16:04

durron597


If the class type is your own code than you can have it implement Comparable and define the compareTo method where you can write the logic. Then, you can compare them using compareTo.

like image 43
Dan D. Avatar answered Apr 11 '26 14:04

Dan D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!