【发布时间】: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 true、return false分支的if。 -
顺便说一句:
name是一个字符串,您应该将其与equals(..)而非this.name == other.name进行比较 -
流派确实为空,但我该如何改变呢?
-
您应该实施
equals(Object o)并进行instanceof检查。编写方法equals(Car other)不会影响例如所有使用equals的集合。 -
@prog:当然,流派是空的。但是您既没有显示
Car的超类的代码,也没有显示调用者的代码...
标签: java nullpointerexception package