Middle+
Can an instance of a user-defined class (class MyType) be a key in a dictionary?
sobes.tech AI
Answer from AI
In programming languages that have dictionaries (hash tables), keys are usually limited to types that support comparison and hashing.
If we talk about a language with classes (for example, Python, Java, C#):
- In Python, instances of user-defined classes can be keys in a dictionary if they correctly implement the
__hash__and__eq__methods. - In Java, objects can be keys in a
HashMapif they implement thehashCode()andequals()methods.
If the class does not override these methods, then keys will be compared by default (for example, by reference), which may be undesirable.
Example in Python:
class MyType:
def __init__(self, value):
self.value = value
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
return isinstance(other, MyType) and self.value == other.value
my_dict = {}
obj = MyType(10)
my_dict[obj] = "data"
Thus, an instance of a user-defined class can be a key in a dictionary if it supports the necessary comparison and hashing operations.