Limnic
Limnic

Reputation: 1876

Generics or Object casting?

Consider this scenario: My goal is to have a small metadata framework. I have a Metadata store which holds pairs of data.

Each pair of data consists of a key (type String) and a value (type MetaValue).

The class MetaValue would hold a single piece of data (not just String) that can be called to work with. It has to be mainly performant because it will be used in the server implementation of a multiplayer game.

Should I keep the data (in the MetaValue class) as an object of type Object and then cast it to whatever I need (like int, boolean, String, ...) or should I make use of generics that returns the data in its original data type form?

I wish to know which of those is the most performant. The data would not be an object of a complex self-made class. It is purely for metadata. For example: the HP of a monster. The attack rate of a weapon, ...

Upvotes: 0

Views: 70

Answers (1)

rgettman
rgettman

Reputation: 178263

If the value of the data could be of any type, then there is no value in generics, which would restrict the data type to a particular class or class hierarchy. Use Object as the data type and cast the data you extract from the metadata object as necessary.

Take care that what you extract is the data type that you expect, or a ClassCastException may result.

This is no more and no less performant than using generics, because when using generics, there would be an implicit cast to the generic type anyway with a method such as Integer hp = metadata.get("monsterHP");.

Upvotes: 2

Related Questions