Menu

#17 Strings compared by reference and not value

open
nobody
None
5
2013-01-10
2005-08-30
Jason
No

I was debugging a similar problem when creating a
Remoting class for writing to indexes and now I'm
having the same problem with searching. I looked at
the source code and there are several occurences
where strings are being cast to objects before they are
compared. Specifically the one that was causing me
trouble was in Term.CompareTo(Term other):

    public int CompareTo\(Term other\)
    \{
        if \(\(System.Object\)

field == (System.Object) other.field)
// fields are interned
return
String.CompareOrdinal(text, other.text);
else
return
String.CompareOrdinal(field, other.field);
}

In this code, field and other.field are both strings.
Casting them to System.Object means that they are
being compared by reference and not by value! In a
single process application, presumably all the fields are
literal constants like "Title" or "Description". I'm
guessing that the compiler creates a single reference for
all identical constant strings throughout the code, so
the references are always equal. In a remoting
scenario, if a term defined in one process is remoted to
another, they will never be equal!

I did a search throughout the source code for a cast to
(System.Object) and all 20 occurrences were strings
being cast to object before being compared (and in
most cases is the field property on Term). My guess is
that whatever tool was used to convert the Java source
code created these casts.

I removed all these casts and my remoting code started
working. Unfortunately I am unable to make the Lucene
unit tests run to verify that it hasn't caused any new
problems. If someone could make this change an run
the unit tests and let me know the outcome, that would
be great!

Jason

Discussion


Log in to post a comment.

MongoDB Logo MongoDB