简体   繁体   中英

Comparing different classes using instanceof

  • Entity.class abstract mother class
  • Player.class extends Entity
  • Wall.class extends Entity
                 public class slkjflksdjf
                 {
                     ArrayList entities = new ArrayList();
                     Player player = new Player();
                     Wall wall = new Wall();

                     public slkjflksdjf()
                     {

                         entities.add(player);
                         entities.add(wall);

                         for(int i = 0; i < entities.size(); i++)
                         {

                             if(entities.get(i) instanceof Wall)
                             {
                                 //do something
                             }

                         }

                     }
                 }

When checking instanceof through my actual full size list of entities it's throwing the "do this" block over and over rapidly, in other words playing an audio clip rapidly lol.. so ye from what i can tell it's treating the Wall and Player both as Entity so doing InstanceOf is just causing it to pull a true even if they are all extensions of the Original Entity?

If both Player and Wall extends Entity interaface you can do following:

ArrayList<Entity> entities = new ArrayList<Entity>();
Player player = new Player();
Wall wall = new Wall();

entities.add(0, player);
entities.add(1, wall);

// entities.get(0) instanceof Player is true
// entities.get(0) instanceof Wall is false
// entities.get(0) instanceof Entity is true

// entities.get(1) instanceof Player is false
// entities.get(1) instanceof Wall is true
// entities.get(1) instanceof Entity is true

for(Entity entity : entities) {

  if(entity instanceof Player) {
    // is player
  } else if(entity instanceof Wall) {
    // is wall
  }

}

hope this helps

If Player is a subclass of Entity and Wall is a subclass of Entity:

player instanceof Entity returns true.

If Wall is a subclass of Entity:

wall instanceof Entity returns true.

However the reverse is not true (.ie entity instanceof Wall) Why? Because that is how instanceof operator is defined.

Moreover if Wall and Player are not related (meaning one is not subclass of the other or implementing in case of interfaces). player instanceof Wall returns false and wall instanceof Player returns false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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