【问题标题】:equals() gives me null pointer exceptionequals() 给了我空指针异常
【发布时间】:2013-02-04 18:41:24
【问题描述】:

这是我的平等方法:

public boolean equals(Car other)
{
if (other == null)
{
    return false;
}

if (this.genre.equals(other.genre))
{

    if (this.price == other.price && this.height == other.height && this.name == other.name && this.door = other.door)
    {
        return true;
    }
    else
    {
        return false;
    }

}
else
{
    return false;
}

}

由于某种原因,这一行给了我一个空指针异常:this.genre.equals(other.genre)

genre 是另一个包中的变量;

所有变量都在类 Car 中声明。该程序编译良好。

这是 Car 的构造函数:

    public Car(double price, float height, String genre, String name, int door)
{
    super(price, height, genre);
            this.name = name;
            this.door = door;

}

为什么会出现空指针异常?

【问题讨论】:

  • 如果genre 为空怎么办...?另请注意,您的内部if 块可以完全折叠为return this.price == other.price 等,而不是带有return truereturn false 分支的if
  • 顺便说一句:name 是一个字符串,您应该将其与equals(..) 而非this.name == other.name 进行比较
  • 流派确实为空,但我该如何改变呢?
  • 您应该实施equals(Object o) 并进行instanceof 检查。编写方法equals(Car other) 不会影响例如所有使用equals的集合。
  • @prog:当然,流派是空的。但是您既没有显示Car 的超类的代码,也没有显示调用者的代码...

标签: java nullpointerexception package


【解决方案1】:

因为this.genre 为空?

if (this.genre != null && this.genre.equals(other.genre))

【讨论】:

  • 这会给你带来奇怪的结果。你在否定string?
  • 应该是this.genre != null
  • 流派不为空,但尝试添加该条件
【解决方案2】:

开始使用在执行字符串比较时正确处理空值的库。

开始使用 apache commons lang。这是StringUtils JavaDoc page

【讨论】:

    【解决方案3】:

    我怀疑您在 Car Object 中与 null String genre 相等,导致 NullPointerExcaption

    if (this.genre!=null && this.genre.equals(other.genre)){...}
    

    还有一件事-

    ...
    if(...this.door = other.door){
               ^^^^
    

    应该是==

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2014-09-06
      • 2014-07-19
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多