views:

195

answers:

1

I would like to know if there is any possible way to retrieve an item from a hashtable using a key that is identical to the actual key, but a different object. I understand why it is probably not possible, but I would like to see if there is any tricky way to do it.

My problem arises from the fact that, being as stupid as I am, I created hashtables with int[] as the keys, with the integer arrays containing indices representing spatial position. I somehow knew that I needed to create a new int[] every time I wanted to add a new entry, but neglected to think that when I generated spatial coordinate arrays later they would be worthless in retrieving the values from my hashtables.

Now I am trying to decide whether to rearrange things so that I can store my values in ArrayLists, or whether to search through the list of keys in the Hashtable for the one I need every time I want to get a value, neither of the options being very cool.

Unless of course there is a way to get //1 to work like //2!

Thanks in advance.

 static void Main(string[] args)
        {
            Hashtable dog = new Hashtable();

            //1
            int[] man = new int[] { 5 };
            dog.Add(man, "hello");
            int[] cat = new int[] { 5 };
            Console.WriteLine(dog.ContainsKey(cat)); //false


            //2
            int boy = 5;
            dog.Add(boy, "wtf");
            int kitten = 5;
            Console.WriteLine(dog.ContainsKey(kitten)); //true;


        }
+8  A: 

Yes, you have two options.

  1. Implement Equals() and GetHashCode() in the key classes.

  2. Create a custom IEqualityComparer and pass it to the Hashtable constructor.

You'll want to implement Equals() and GetHashCode() yourself when the implementations make sense for all usages of your custom class. If they are only appropriate sometimes, then use a custom IEqualityComparer which has the same functionality but provides it separate from the class itself. This second option also allows you to provide custom rules for non-custom key classes.

Sam
+1 for option 2 (since he can't very well inherit from `int[]`)
Adam Robinson
Another +1 for option 2. Though I'd strongly recommend changing the design of the app to use a more suitable key.
Josh Einstein