Can a Hash have duplicate keys or values?
This question is going to depend heavily on the hash table itself, since both are possible. For example, std::unordered_map doesn't allow duplicates, while std::unordered_multimap does allow duplicates.
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.
A hash table stores key and value pairs in a list that is accessible through its index. Because key and value pairs are unlimited, the hash function will map the keys to the table size. A hash value then becomes the index for a specific element.
Short answer is no, hashes need to have unique keys.
Please try and run this code, it executes without errors. I hope this is what you were asking!
#!/usr/bin/perl
use strict;
use warnings;
my %hash = ('a' => 1, 'a' => 2, 'b' => 4 );
print values %hash, "\n\n";
print keys %hash, "\n\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With