Have additional class "stored" in a Player object

I currently store a custom class that contains additional information for each online player in a Map< UUID, AdditionalClass>. I often need these additional informations in events where I only got the Player available and I fear, that it might be bad for performance to iterate over each player to find it’s additional class. Is there a way to “store” a class in a Player and later access it when you need it?

You can use custom DataManipulators.

  • Create two classes - one implementing DataManipulator and one implementing ImmutableDataManipulator.
  • Create a DataManipulatorBuilder for the DataManipulator class.
  • Register both builders with the DataManager via register(manipulatorClass, immutableManipulatorClass, builder).
  • To add your data to the player, create an instance of your manipulator and pass it to player.offer().
1 Like

Definitely check out custom data as @JBYoshi says.

You don’t need to do this because you can just look up the UUID in the map. something like:

AdditionalClass data = theDataMap.get(player.getUniqueId());

This is a perfectly fine way to do it.

1 Like

I’m using get() but doesn’t the the map have to iterate over its items to find something? If it’s a perfectly fine way to do it, I probably will keep it that way because I would have to change big parts of my project.

No, that’s the point of a hashmap, it’s a O(1) operation

From HashMap (Java Platform SE 8 )

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

1 Like

Ok. That’s nice :smiley:

It depends on the map implementation, But hashmaps are actually really fast at fetching keys due to a few tricks they have, if you havn’t already it’s really an eye opener to see how it’s done.

1 Like

Thanks. This was really helpful :slightly_smiling:

It depends on many things. It’s usually O(1), with a decent hash which itself is constant time… but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match.

In the worst case, a HashMap has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn’t come up very often in real life, in my experience. So no, O(1) certainly isn’t guaranteed - but it’s usually what you should assume when considering which algorithms and data structures to use.