# Classes as HashMap keys

This topic is 1371 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm working on a 2D game engine in Java that uses an entity-component based system, but I seem to have hit a snag designing my base entity class. I have it set up so that when you add a component, it adds it to a private HashMap in the entity class with it's class as it's key:

private final HashMap<Class<? extends Component>,Component> components;
public void addComponent(Component component){
components.put(component.getClass(), component);
}

The problem arises when I call my getComponent() method:

public <T extends Component> T getComponent(Class<T> type){
return (T) components.get(type);
}


This works most of the time, but not when I want to retrieve a Component that is also a subclass of a more general class. For example, I have two types of sprite classes: StaticSprite and AnimatedSprite, both extending from an abstract Sprite class. As far as game scripting is concerned, you'd never have to deal with the specific types of sprites, just the general Sprite class, so you'd create sprites like this:

Sprite sprite = ResouceLoader.loadSprite("data/sprites/testanimatedsprite.xml"); //Returns an AnimatedSprite


The problem is, once I add this sprite to a component and try to retrieve it using getComponent() like this,

Sprite sameSprite = entity.getComponent(Sprite.class);
sameSprite.doSomething();


I end up getting a NullPointerException as it searches for a Sprite, but it's actually stored as an AnimatedSprite in the HashMap.

My question is, is there any way to do this so I can add/retrieve components from this HashMap by a it's superclass without having to explicitly declare the key in addComponent() or use the more specific class in getComponent()?

Edited by duktapeman90

##### Share on other sites

As it is, I doubt it.

You're using Component runtime classes as "categories" more or less. So you end up adding a component in the, say, StaticSprite category, but trying to retrieve it from the Sprite category.

You could create some concept of "slot". Maybe an index. Each Component type has an index, so when you add that Component to an Entity, it goes into that index. Sprite would define its own index, and subclasses of it would end up in that same slot.

Thing is that retrieval would depend on implicit knowledge. Ie, you would end up trying to retrieve a Sprite from an entity and casting it to StaticSprite or AnimatedSprite somewhere along the road, and there is no guarantee the Entity has one or the other. It isn't very safe.

Now, outside of the specific problem at hand, why do you have a StaticSprite and an AnimatedSprite? AFAIK the ECS approach is to separate behavior by separating the components, sprite is one behavior, animation is other, so you'd have Sprite component and Animation component.

Off the top of my head (thus possibly not adapted to your actual needs), Sprite would hold the current Sprite frame that has to be drawn, Animation would hold the data of the rest of the animation frames, AnimationSystem would grab your Animation and Sprite components, and update the Sprite with the next frame the Animation component holds.

##### Share on other sites
AFAIK the ECS approach is to separate behavior by separating the components, sprite is one behavior, animation is other, so you'd have Sprite component and Animation component.

I agree but if you want to have one object with 2 animated sprite, you will have to link each animation component with the sprite component.

--

Why do you use a hashmap ? One flat array with a linear search is enough, you will never have a lot of component in an object.

Edited by Alundra

##### Share on other sites

Now, outside of the specific problem at hand, why do you have a StaticSprite and an AnimatedSprite? AFAIK the ECS approach is to separate behavior by separating the components, sprite is one behavior, animation is other, so you'd have Sprite component and Animation component.

+1 for that!

The Object.getClass() method in Java doesn't behave as you want it to.  It will always return the deepest child class, even from a parent class. So that's not going to do what you want.  You can get around this by using the static class reference: MyObject.class, but that doesn't help you at run time.

Since you need to have objects that are composed of many different types you'll need to store them a different way.  Maybe just a hash of the different component types?

##### Share on other sites
The usual ways of solving this are one of:

a) Use "slots" as a prior poster said. Each Component subclass overrides a GetComponentClass that returns the appropriate class type that you want to register with.

b) Always register only the direct descendent class of Component. When you get a class descriptor, iterate up the base chain until your base is Component.

c) Register the component under all the Component descendent types. That is, if you register StaticSprite which derives from Sprite, you'd walk up the bases registering the component under each base until you hit Component. So the component would be registered both as StaticSprite and Sprite.

If you want to be using a real ECS architecture, though, then you have no need of this map in the first place. If you want to know if an entity has a certain component or retrieve that component type, you just query the entity's ID against the component's system, e.g. StaticSpriteComponent sprite = graphics.GetStaticSpriteComponentSystem().LookupComponent(my_entity_id);

##### Share on other sites

As others have implied, you really have two architectural options (ignoring various hacks to work around the current semantics):

• Move to an outboard component system, where you query sprites from the external SpriteSystem, which understands the difference between static and dynamic sprites, or
• Get rid of the multi-level inheritance, either by collapsing StaticSprite and AnimatedSprite into a single, optionally animated class, or by separating them entirely and make each inherit directly from Component.

Note that the two options are not mutually exclusive, and might well both be considered desirable. The path you are currently going down is likely to result in many of the same issues that an ECS is designed to avoid in the first place (i.e. deep inheritance, poor cache locality, etc).