Joc*_*lde 1 java arrays equals object instance
如果这个问题已经得到回答,我很抱歉,虽然我确实有一个广泛的外观,但无法找到答案.总结一下情况我试图创建一个模拟器程序,处理不同的捕食者和猎物生物,目前有让每个生物检查它旁边的生物类型的问题,我更愿意检查是否instance属于同一个对象.
所以说例如我做了这个:
private class Creature {
...
Creature [] fish = new Creature();
Creature [] shark = new Creature();
Creature [] penguin = new Creature();
}
Run Code Online (Sandbox Code Playgroud)
然后在循环中创建每个类型的几个实例(生物),如下所示:
for (int f=1;f<rnd;f++) {
fish[f] = new Creature();
//set attributes of creature
Run Code Online (Sandbox Code Playgroud)
然后程序可以告诉他们相对于彼此的位置我创建了一个网格系统,如下所示:
Creature [][] gridloc = new Creature[x][y]; //relates to number of spaces tiles that determines movement.
Creature [] crloc = new Creature[tc]; //stores a reference to all creatures created.
...
crloc[tc] = fish[f]; gridloc[x][y]=crloc[tc] //or fish[f]
}
Run Code Online (Sandbox Code Playgroud)
无论如何总结甚至我在那里总结了相当多的代码,这一切都有效,但是当让每个生物在gridloc中检查旁边有什么例如捕食者时我不确定是否找到另一个生物来检查确定这是同一对象类型的实例还是不同的实例.所以类似于:
if (!gridloc[x][y].getObject().equals(gridloc[x+1][y].getObject()) //if the current creature is not the same as the one next to it.
Run Code Online (Sandbox Code Playgroud)
我知道像instanceof这样的东西但只能检查一个对象是否是一个类的实例,而不是一个实例属于同一类型的对象.我也不能简单地使用fish [1] .equals(fish [2]),因为它们具有不同的属性,并且会检查它们是否完全相同.
任何想法/建议都会受到欢迎.谢谢!
您需要研究多态性(http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html).您将Creature声明为基类(或接口),并为您拥有的每种类型的生物从Creature类扩展/实现.每个子类都将实现它自己的方法来覆盖Creature,并允许您正确使用这些方法,并使用每个实例将具有的类元数据来检测类型.