Comparing two instances of a class in Java

java

Solution

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;
  }   
}

Problem

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?

Original source