You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@lucenenet.apache.org by George Aroush <ge...@aroush.net> on 2006/09/01 05:49:40 UTC

RE: C#.GetHasCode() and Java.hasCode()

Hi folks,

I am posting this on both Lucene.Net list in hope to cover wider audience.

A good number of NUnit tests under Lucene.Net 2.0 are failing due to the way
GetHasCode() is working in C# compared to Java.

The following code in C#:

    System.Collections.ArrayList source = new
System.Collections.ArrayList();
    System.Collections.ArrayList cloned;

    // source.Add("one");  // those two "Add" lines won't make a different
    // source.Add("two");

    cloned = (System.Collections.ArrayList) source.Clone();

    System.Console.WriteLine("source: " + source.GetHashCode());
    System.Console.WriteLine("cloned: " + cloned.GetHashCode());

will giving you back a different hash value for "source" and "cloned" -- but
in Java they will be the same.

My question is the following, is this expected of C# or is my code buggy?
If this is expected of C#, what suggestion do you have to over come this
issue?

The solution I put in is to iterate over the list and get the hash value one
item at a time like so:

    int hashCode = 0;
    for (int i = 0; i < source.Count; i++)
    {
        hashCode += clauses[i].GetHashCode();
    }

Any comment, suggestion?

Regards,

-- George Aroush


RE: C#.GetHasCode() and Java.hasCode()

Posted by Dean Harding <de...@dload.com.au>.
> A good number of NUnit tests under Lucene.Net 2.0 are failing due to the
> way GetHasCode() is working in C# compared to Java.

ArrayList list doesn't explicitly implement GetHashCode(), and simply
inherits the implementation from System.Object, which just returns a value
based on the reference's address (so two different objects will return a
different hash code, whether or not they're semantically the same).

> int hashCode = 0;
> for (int i = 0; i < source.Count; i++)
> {
>     hashCode += clauses[i].GetHashCode();
> }

Your solution is OK. Another would be to inherit from CollectionBase (or
even better would be to inherit from List<T>) and add your own
implementation.

One question I would ask is, why does it expect the hash codes to be the
same anyway? Wouldn't it be better to just check for actual equality
(because even if the hash codes are the same, you'd have to do the full
check anyway)

Dean.