【问题标题】:Error in using instanceOf operator in Java在 Java 中使用 instanceOf 运算符时出错
【发布时间】:2021-11-09 17:48:12
【问题描述】:

不确定第 24 行出了什么问题。我正在尝试重写 Object.equals() 方法,但由于该方法采用 Object 类型,我想过滤掉不是 Employee 实例的输入。这是一个java入门课程

我收到以下错误:

4 errors found:
File: /Users/wesley/Documents/Employee.java  [line: 24]
Error: ')' expected
File: /Users/wesley/Documents/Employee.java  [line: 24]
Error: variable declaration not allowed here
File: /Users/wesley/Documents/Employee.java  [line: 24]
Error: ';' expected
File: /Users/wesley/Documents/Employee.java  [line: 30]
Error: 'else' without 'if'

这是代码。

//employee number, name, and salary
public class Employee{
  private String name;
  private final int ID;
  private double salary;
  private static int lastID;
  public Employee(String name, double salary){
    this.name=name;
    ID=Employee.lastID+1;
    this.salary=salary;
    Employee.lastID=Employee.lastID+1;
  } 
  public String getName(){return name;}
  public int getID(){ return ID; }
  public double getSalary(){ return salary;}
  public void setName(String newName){name=newName;}
  public void raise(double newSalary){ salary=newSalary;}
  @Override
  public String toString(){
    return "Name: "+ getName() + "\nID: " + getID() + "\nSalary: " + getSalary();
  }
  @Override
  public boolean equals(Object o){
    if(o instanceOf Employee){//errors are here!
    Employee input=(Employee) o;
    if(this.getSalary()==input.getSalary() && this.getName().equals(input.getName())){
      return true;
    }
  }
    else{return false;
    }//another error here
      }
    }

懒得修复缩进。刚刚在我粘贴东西时发生了

【问题讨论】:

  • 欢迎来到 SO,问题是没有名为 instanceOf 的操作数它被称为 instanceof。作为旁注,我会将 if 条件翻转为 if (!(o instanceof Employee)) { return false },您不需要 else 子句,它会使事情更容易阅读。

标签: java equals instanceof


【解决方案1】:

它是instanceof,带有小写的o,而不是您现在使用的“instanceOf”。更正此错误后,您可以看到并非该方法的所有分支都有 return 语句 - 如果输入了第一个 if 而第二个没有,会发生什么情况?

简化布尔条件和多余的else 语句可以解决这个问题:

@Override
public boolean equals(Object o){
    if (o instanceof Employee) { // instanceof instead of instanceOf
        Employee input=(Employee) o;
        return this.getSalary() == input.getSalary() && 
               this.getName().equals(input.getName());
    }
    return false;
}

【讨论】:

    【解决方案2】:

    有很多事情可以改进。

    首先,instanceof关键字是小写的。

    其次,如果您覆盖equals(Object),您还必须覆盖hashCode(),如this answer 中所述。这个答案还包含如何实现equalshashCode 的优秀示例。

    第三,您的实现允许name 成为null,在这种情况下this.getName()null 和您的支票

    this.getName().equals(input.getName()) 
    

    抛出NullPointerException。我建议您遵循answerthis tutorial 中更强大的做法,或者通过在构造函数和setName 中检查它来确保name 永远不会是null

    其他改进和备注

    如果有一个字段ID,我假设它在那里识别员工。在这种情况下,它必须包含在equals 检查中

    如果有“ID”,为什么还要检查姓名薪水?改变salary是否也意味着它变成了一个不同的Employee?如果我更正了员工的姓名,也一样?

    ID 的初始化不是线程安全的,并且可能导致不同的Employees拥有相同的ID。考虑做:

    import java.util.concurrent.atomic.AtomicInteger;
    ///
    private static AtomicInteger lastID = new AtomicInteger();
    

    然后在构造函数中做

    this.ID = lastID.getAndIncrement();
    

    这使得以下行变得不必要:

    Employee.lastID=Employee.lastID+1;
    

    另一件事是raise 方法还允许将薪水设置为低于其先前的值。我要么检查一下,要么将raise 重命名为setSalary

    考虑到这一切,它会导致类似:

    import java.util.Objects;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Employee {
        private static AtomicInteger lastID = new AtomicInteger();
        private String name;
        private final int ID;
        private double salary;
    
        public Employee(String name, double salary) {
            this.name = name;
            ID = lastID.getAndIncrement();
            this.salary = salary;
        }
    
        public String getName() { return name; }
    
        public int getID() { return ID; }
    
        public double getSalary() { return salary; }
    
        public void setName(String newName) { name = newName; }
    
        public void setSalary(double newSalary) { salary = newSalary; }
    
        @Override
        public String toString() {
            return "Name: " + getName() + "\nID: " + getID() + "\nSalary: " + getSalary();
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Employee)) return false;
            Employee employee = (Employee) o;
            return ID == employee.ID;
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(ID);
        }
    }
    

    【讨论】:

    • 我个人认为AtomicInteger 有点过分了:)。围绕ID 的问题很有趣,两个对象是否具有相同的 id 但其他字段的不同值相等?无论如何都赞成包含实现hashcode 和相当简洁的equals 方法:D
    • @Gavin 也许,但来自高度并发的地方它是一种自动的。 ID=lastID++ 也很自然。
    • 感谢您非常详细的回复!这只是一个课堂示例,但了解所有这些实际考虑因素会很有帮助:)
    猜你喜欢
    • 2012-07-29
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多