简体   繁体   中英

Comparing two instances of a class in 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?

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

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 .

你可以实现和使用comparablecomparator

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