Page 1 of 1

Dictionary Commands

PostPosted: Mon Nov 03, 2008 7:20 pm
by Imagine3163
So I was playing around with Cobra's Dictionary class today and I was wondering if there was an easier way to get values from a key instead of having to subscript it? Currently this is what I am doing:

Code: Select all
myDictionary = Dictionary<of Foo, List<of List<of Bar>>>()

#This throws a KeyNotFoundException...even though I know for a fact that fooObject IS in the
#dictionary
print myDictionary[fooObject].count


Is there any reason anyone can think of as to why it is doing this? The only thing I can think of is that it is comparing by memory addresses instead of by the fooObject's value

So, I was wondering if there is some kind of .get method or something like that which will take a Foo object as the key and return the list of values.

Re: Dictionary Commands

PostPosted: Mon Nov 03, 2008 8:30 pm
by Charles
Even if there were a separate .get method, it would use the same mechanisms as the indexing/brackets. But here is some help:

Cobra's dictionaries are just the dictionaries straight out of the .NET/Mono libraries. Regardless of which .NET language you use, if you are using a custom class or struct Foo as a key, you often need to override .equals and .getHashCode in Foo. These are used by the dictionary implementation.

The same holds true if you are putting the Foos in Set collections (which come with Cobra, but not .NET).

Without the overrides, I think the dictionary will just use the memory address as the "key" for comparisons and equality tests. That works if your objects are kept unique.

Here's an example:
# disclaimer: untested

class Employee

var _name as String
var _idNumber as String

def init(name as String, idNumber as String)
require
name.trim <> ''
idNumber.trim <> ''
body
_name = name
_idNumber = idNumber

get name from var

get idNumber from var

def toString as String is override
return '[.getType.name]("[.name]", [.idNumber])'

def equals(other as Object) as bool is override
if this is other, return true
if other inherits Employee
return .idNumber == other.idNumber
else
return false

def getHashCode as int is override
return .idNumber.getHashCode

Also, if you want dump the keys in a dictionary:
for key in d.keys, print key

Also, I find it helpful sometimes to take something like "List<of List<of Bar>>" and make a subclass out it like so:
class BarMatrix
inherits List<of List<of Bar>>
pass

One benefit is readability. Now you can say "Dictionary<of Foo, BarMatrix>". Another benefit is that you can add utility methods to BarMatrix as you see fit.

HTH. Let us know how it goes.

Re: Dictionary Commands

PostPosted: Mon Nov 03, 2008 9:54 pm
by Imagine3163
Thanks so much Chuck! That was exactly what I needed to do. I just overrode the .equals and the .getHashCode methods in my custom class and it worked just great!

Re: Dictionary Commands

PostPosted: Mon Nov 03, 2008 10:46 pm
by Charles
Glad I could help.