java - 创建 equals 方法

标签 java equals

根据作业,我必须创建一个名为“equals”的方法来执行以下操作:

The method compares the instance variables of the calling object with instance variables of the parameter object for equality and returns true if the dollars and the cents of the calling object are the same as the dollars and the cents of the parameter object. Otherwise, it returns false.

更新:我犯了一个错误,放错了内容,已更新。出现新错误:

Money.java:115: error: long cannot be dereferenced
  if (dollars.equals(otherObject.dollars) &&
             ^
Money.java:116: error: long cannot be dereferenced
     cents.equals(otherObject.cents))
          ^
2 errors

使用方法:

   public boolean equals(Money otherObject)
{
  boolean status;

  if (dollars.equals(otherObject.dollars) &&
     cents.equals(otherObject.cents))
    return status = true;
  else
    return status = false;
}

最佳答案

dollarscents 是原始 long 类型吗?

如果是的话,您需要使用 (dollars == otherObject.dollars) && (cents == otherObject.cents) 。您无法在基元上调用方法(例如 equals())。

关于java - 创建 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22463171/

相关文章:

java - 如何在不使用 IDE 的情况下在 Linux 上运行 Java 项目

java - 处理一些运行时 HTTP 异常的好的做法是什么?

java - 可变集合应该覆盖equals和hashCode吗?

Java 显示正确 错误

java - 在 equals 方法中避免 instanceof 的可行方法?

java - 为什么在 Java 中使用 HashMap 会失败?

java - contains方法忽略等于重写

Java父子函数调用机制关系

java - 用窗口求和

java - 如何使用 Spring Data JPA 发出修改查询以通过其 ID 删除一组实体?