Is there a cleaner way to give dictionary-like access to a list?

Viewed 80

I have a chunk class and I want it to contain references(represented by a int identifier) to objects that are occupying certain coordinates in the chunk. Since many objects don't have collisions, the same position may be occupied by multiple objects. The chunks have 2 dimensions (x,y). Here is what I was thinking to achieve this:

public class Chunk{

public List<int>[] objPresence;

}

This would make an array of lists( in which size = chunksizeX * chunksizeY) where the index would be the flattened x,y coordinates, and the list would contain all objects on that position. ( each int in the list would be my identifier of a given object )

So to find what objects are currently in a given position I would do:

listOfObjectsOnPosition = objPresence[ flattenIndex(x,y) ];

So far so good, but now if I want to check if one specific object is in a certain position I have to iterate through the list, and I would like to be able to have O(1) access on this.

So here is the alternative using dictionary:

public class Chunk{

public Dictionary<int,byte>[] objPresence;

}

and for access, to find a certain object:

objPresence[ flattenIndex(x,y) ].ContainsKey(objToSearch)

I can also iterate through the dictionary keys if I just want to get all objects in the position.

However in this method since I am using Dictionary, and the int key is the identifier for the object, the byte value on the dictionary is wasting memory since i dont need that value for anything.

Is there a way to implement what I have here without that wasted byte, or is there another, better way to do this altogether?

Thanks!

0 Answers
Related