开发者

Is it a bad idea to use recordId as hashcode?

Suppose I have a simple DTO object right out of the database, and the Id is a recordId that is definitely unique, is it a good idea then to do the following ?

public class DTO
{
    public int Id { get; set; }

    public override bool Equals(object obj)
    {
        return (Id == ((DTO)obj).Id);
    }

    public override int GetHashCode()
    {
        return Id;
    }
}

Th开发者_开发问答e reason I doubt it a bit is because I don't see it in code around me, as opposed to code like

int hash = 7;
hash = 89 * hash + pageId.hashCode();
hash = 89 * hash + recordId;
return hash;


The contract for a hash code is "two equal objects must have the same hash code". That implies that any fields used in determining equality must be represented in the bits that make up the hash code. Since your equality contract refers only to the ID, then that's the only thing required in the hash code.


A good hash function is supposed to (more or less) randomly distribute the hash values, so that when you put the hash values into a binary tree, you get a good, evenly distributed tree, and not one that is just a linked list down one side.

See here: http://blogs.oracle.com/kah/entry/the_importance_of_good_hash

But if you never have this need (i.e. you will always be returning records from the database, rather than looking them up from your own binary tree), then using the id as the hash seems perfectly reasonable to me.


Since the int already has a method for getting the hash code, I would just use that one.

public override int GetHashCode()
{
    return Id.GetHashCode();
}


If your class only contains an integer, you can use that as hash code. That's the same as the implementation of the Int32.GetHashCode method that just returns the integer itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜