简体   繁体   English

无法从哈希表中的对象调用方法

[英]Can't invoke a method from an object in a hashtable

so all I'm trying to do is create this object and then store it and others like it in a hashtable and then use ones of its methods later. 所以我要做的就是创建这个对象,然后将它和其他类似的对象存储在哈希表中,然后再使用其中的一些方法。 But when I try and get the object and use its method I get an error. 但是,当我尝试获取对象并使用其方法时,出现错误。

My Code: 我的代码:

D_Object obj;
Hashtable player_table;

obj = new D_Object("pikachu",pikachu,PLAYER_X,PLAYER_Y,PIKA_WIDTH,PIKA_HEIGHT,PIKA_OFFSETX,PIKA_OFFSETY,PLAYER_SPEED);

player_table.put(obj.getObjNum(),obj);

....then later I try and use the objects method getObjNum() and it gives me an error ....然后,我尝试使用对象方法getObjNum(),它给我一个错误

for(int i=1;i<=obj.getNumObjs();i++){
    if(player_table.get(i).getObjNum() != obj.getObjNum()){

.... ....

the error is as follows: 错误如下:

appletGameExample.java:319: cannot find symbol
symbol  : method getObjNum()
location: class java.lang.Object

It gives the same error for any time I try and use the methods from this object 每当我尝试使用此对象的方法时,它都会给出相同的错误

Can someone please help? 有人可以帮忙吗?

用作Hashtable<int, D_Object>

Because you don't specify what kind of objects the Hashtable holds, it retrieves them as Object by default (the class that everything extend s). 由于您没有指定Hashtable持有的对象类型,因此默认情况下,它会将它们检索为Object (所有内容都extend为的类)。 An Object doesn't have the methods you're trying to invoke on it. Object没有您要在其上调用的方法。 You will need to perform type-casting upon accessing them, or specify what the Hashtable holds, like so: 您将需要在访问它们时执行类型转换,或指定Hashtable ,如下所示:

Hashtable<String, D_Object> player_table = new Hashtable<String, D_Object>();

((D_Object)player_table.get(i)).getObjNum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM