Re: String comparison with "==" is not reliable?



Jason Cavett wrote:
== is reliable, but not for what you're trying to do. == compares the
object's references. .equals() compares the actual string value
(which is what most people are trying to do). This is the case with
any object. AFAIK, the only time == actually compares values is if
you're comparing primitives (ints, double, floats).

Not quite. By default, equals() compares references, not values of the objects themselves ("string" or otherwise). Only if equals() is overridden does its behavior change, and then to that of the override, which is entirely up to the programmer.

In the case of String, equals() has been overridden to compare the chars in the String value for equality. In the case of Integer, equals() has been overridden to compare the wrapped int values for equality. Other classes override equals() differently, or not at all. If they do not override equals(), it behaves just like ==.

If you override equals(), you had better override hashCode(), and vice versa.

--
Lew
.



Relevant Pages

  • Re: comparing objects
    ... I override the Equal method on SalesRegion ... As Arne already put it, the Contains method is using the Equals method, ... ArrayList salesRegions = ... private string s; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Problem with String class
    ... The equals() method compares the characters that make up String ... String objects into two char arrays and comparing the two arrays. ...
    (comp.lang.java.programmer)
  • Re: Comparing strings (with typos)
    ... I don't think probability and equality mesh well. ... I'm very much in need for a routine that compares 2 strings. ... How can you get a probability that the second string equals ...
    (microsoft.public.access.modulesdaovba)
  • RE: Equality vs Sameness
    ... Equals would not offer any benefit. ... >> from it in the future if the users haven't asked for that functionality. ... So you override Equals and GetHashCode even for forms, ... or wanted to compare two instances of a singleton? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Function that returns date of file.
    ... string after the date/time when it is used by itself. ... Is that your entire script? ... I make an IF statement that required the 'equals equals'. ... designed database your job will be all that much harder. ...
    (alt.php)