简体   繁体   English

比较Java中两个类的实例

[英]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 如果声明需要返回true

instance1.blockNumber < instance2.blockNumber;

or 要么

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

As far as I know Java doesn't support operator overloading. 据我所知,Java不支持运算符重载。 How can I do this such comparison? 我该怎么做这样的比较?

Have the class implement the Comparable interface, which gives the compareTo method. 让类实现Comparable接口,它提供compareTo方法。 You can then use the value of the number ( -1 for less, 1 for more, 0 for equals) in your if statements. 然后,您可以在if语句中使用数字的值( -1表示less, 1表示更多, 0表示equals)。

If you want to put these objects in lists (say, for sorting) you should also @Override the .equals method. 如果你想要把这些对象在列表中(比如,用于排序),你也应该@Override.equals方法。

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. 如果类类型是您自己的代码,那么它可以实现Comparable并定义compareTo方法,您可以在其中编写逻辑。 Then, you can compare them using compareTo . 然后,您可以使用compareTo比较它们。

你可以实现和使用comparablecomparator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM