0

Considering the following example:

class Person {
    int citizenNumber; // key
    int age;
    string name;
    constructor(citizenNumber, age, name);
}

Map<int, Person> personsMap = {};
//Map allows the inconsistency fault: key != citizenNumber (object key)
personsMap.put(1, new Person(2, 18, "John"));

// Set would allow this if search by a key was possible
Set<Person> personsSet = { new Person(1, 20, "Paul") };
int searchableCitizenNumber = 1;

// Person should implement/extend some key like `key => citizenNumber`
Person person = personsSet.get(searchableCitizenNumber);

Is there any data strucuture that:

  • Does not allow duplicates
  • Allow queries from a given key stored in the object itself
Exprove
  • 1,301
  • 2
  • 18
  • 32
  • 4
    Just wrap the map in another object that doesn’t expose the `put` method but offers an appropriate `add` and `get` method. – Holger Jan 03 '23 at 14:46
  • Here is an example of sub-classing a dictionary (map) to behave in this way. The constructor accepts a property expression that is automatically used to select the key from inserted elements. https://stackoverflow.com/a/42282673/529618 – Alain Jan 04 '23 at 15:35

0 Answers0