Dictionary vs. Hashset

HashSet

  • Does not allow for duplicate values
  • unordered collection for containing unique elements
  • Hashset<TValue> hSet = new HashSet<TValue>();

Dictionary (Hash Table / HashMap)

  • Does not allow for duplicate values but also does not allow for
  • Unordered collection of keys and values.
  • Dictionary<TKey, TValue> is implemented as a hash table

Similarities

  • Both use hashes to access variables
  • Both are unordered

Equals vs. GetHashCode

public int FooId { get; set; }
    public string FooName { get; set; }
    public override bool Equals(object obj)
    {
        Foo fooItem = obj as Foo;

        return fooItem.FooId == this.FooId;
    }
    public override int GetHashCode()
    {
        // Which is preferred?

        return base.GetHashCode();

        //return this.FooId.GetHashCode();
    }
  • Equals is used in this case when the hash codes for two things match. This is ESPECIALLY important in hash maps/dictionaries.

If there is no collision, equals won't be called.

  • GetHashCode will be called firs to see the hash code for the given object. If it doesn't match another hash code or there is no collision, equals will not be necessary.

Equals will be called when GetHashCode finds a collision.

  • If Equals() returns true, then GetHashCode must be equal for both values.
  • They don't necessarily have to be the same. This just means there is a collision. Equals is then called to check if they're the same key-value pairing.

Equals vs. ==

  • Equals is just a virtual method.

Why Structs are Value Types even though they can be New'd

Garbage Collection (LOH and Why it's bad)

const vs readonly

IDisposable and how to Implement

Type Boxing and Typing in General

results matching ""

    No results matching ""