G
G
Georgy Pelageykin2016-08-04 13:55:34
Mono
Georgy Pelageykin, 2016-08-04 13:55:34

Is it legal to return the ordinal number of an object in GetHashCode()?

Good day. There is this code:

namespace Stardust.Core.World
{
  public class SpaceObject
  {
    public SpaceObject()
    {
      LastLeasedID++;
      ID = LastLeasedID;
    }

    /// <summary>
    /// Уникальный идентификатор этого объекта. Не может быть изменен после создания.
    /// </summary>
    public readonly Int32 ID;

    public override Boolean Equals(Object obj)
    {
      var o = obj as SpaceObject;
      if (o != null)
        return this.ID == o.ID;

      return false;
    }

    public Boolean Equals(SpaceObject other)
    {
      return other != null && this.ID == other.ID;
    }

    public override Int32 GetHashCode()
    {
      return ID;
    }

    public static Int32 LastLeasedID { get; private set; }
  }
}

Those. this is an object that always has a unique identifier, also known as a serial number. Question: is such an implementation of GetHashCode correct in this case (equals seems to be logical)? In particular, won't there be problems with a dictionary containing a couple of tens/hundreds of such objects? There is a suspicion that such a non-uniform distribution will be bad for the implementation of hashing in a dictionary and there will be many collisions, but I'm not sure.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrew, 2016-08-04
@ArXen42

GetHashCodeThe and methods Equalsmust be overridden if you want two different instances of the same class to be considered the same . In your case, the instance will only be equal to itself, because they Idwill always be unique. It turns out that you have reinvented the comparison semantics by reference, which already works by default, if not overridden at GetHashCodeall Equals.
Another problem will arise if you use this code in a multi-threaded environment - without synchronization of access to, LastLeasedIDsooner or later you will get duplicates.

V
Vitaly Vitrenko, 2016-08-04
@Vestail

Universal hash code override rule by Joshua Bloch

Store some constant nonzero value, say 17, in an int variable called result.
Compute an int hashcode c for each field f that defines equals:
Using just the id is fine, but it needs to be multiplied by some number.

K
Konstantin Berdnikov, 2016-08-04
@Toisen

You are definitely reinventing the wheel. Almost any IDE has a function to automatically generate these methods with the ability to select the fields that will be taken into account.
As for this implementation, there is a similar example in the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question