Interesting generics..

So today I learnt some generics :smiley: Maybe someone will find this useful! :smiley:


	@SuppressWarnings("unchecked")
	public <T extends Entity> T getEntityWithTag(Class<T> type, String tag) {
		for (int i = 0; i < entities.size(); i++) {
			Entity entity = entities.get(i);
			if (entity.tag.equals(tag) && entity.getClass().isAssignableFrom(type)) return (T) entity;
		}

		return null;
	}

Quick explanation:
Entity.tag is a String;
isAssignableFrom(Class) basically means instanceof

What this method does, is basically take a class that extends entity, and some kind of tag. Check all the existing entities to see if there is an entity which is instanceof class specified and with tag specified and return the class specified if it finds that entity. No idea if I explained properly, but here you go :smiley:

Whether this is a good idea depends on how often you call [icode]getEntityWithTag(type, tag)[/icode]. Building a proper data-structure allows for retrieval of subsets of data at O(1) instead of O(n), but you pay the price in maintaining these data-structures.

So depending on whether this underlying structure is often written into (adding, removing, changing entities), the current approach may or may not be sensible, performance wise – design wise it’s… a poorly named method, it should be [icode]getFirstEntityWithTag(type, tag)[/icode]

cant you just make an ID field that maps a constant to an entity type ? everytime you use reflection a kitty dies ):

Using a hashmap with key of {type,String} is the same amount of programming work.

Hmmm… I think you misunderstood me kinda.

The thing I found interesting is that this method returns the type that you put it. So if you do findEntityWithTag(String.class, “whatever”) it would return a string object.

Thats what I found interesting :smiley:

Well, that’s generics for ya. :slight_smile: