【问题标题】:New to Java and have the error "int cannot be dereferenced"Java 新手并出现错误“无法取消引用 int”
【发布时间】:2013-04-07 00:04:53
【问题描述】:

我是 java 新手,我一直在做这个练习,但一直收到错误:无法取消引用 int。我看到了几个类似的问题,但仍然无法弄清楚我自己的情况。 以下是完整代码:

package inclass;

class OneInt {
  int n;

  OneInt(int n) {
    this.n = n;
  }

  @Override public boolean equals(Object that) {
    if (that instanceof OneInt) {
        OneInt thatInt = (OneInt) that;
        return n.equals(thatInt.n); // error happens here
    } else {
        return false;
    }
  }

  public static void main(String[] args) {
    Object c = new OneInt(9);
    Object c2 = new OneInt(9);
    System.out.println(c.equals(c2));
    System.out.println(c.equals("doesn't work"));
  } 
}

非常感谢你帮我解决了这个小麻烦。

【问题讨论】:

    标签: java


    【解决方案1】:

    equals 是一个类的方法。 int 是原语,而不是类。只需改用==

    return n == thatInt.n;
    

    【讨论】:

      【解决方案2】:

      要比较ints,只需使用== 运算符:

      if (n == thatInt.n)
      

      请注意,int 不是一个类,因此您可以永远. 运算符与int 变量一起使用。

      【讨论】:

        猜你喜欢
        • 2019-03-09
        • 2013-09-16
        • 2017-12-20
        • 1970-01-01
        • 2016-05-09
        • 2016-02-21
        • 1970-01-01
        • 2023-03-31
        • 2014-11-23
        相关资源
        最近更新 更多