Re: do I need to override the equals() method?



Albert <albert@xxxxxxxx> wrote:
Marteno Rodia a écrit :
I've defined a class which, of course, silently extends
java.lang.Object, but I've added some my own attributes. Now I want to
be able to compare two objects of my class i.e. to check if they are
identical.

If you want to check for *identity*, then you can just use the inherited
Object.equals() and ignore the rest of this posting.

Do I need to write my own equals() method or can I use the
inherited java.lang.Object.equals() method?
so if you want that equals returne true for "content identical" object,
yes you should override the equals(Object) method.
It depends on your uses. If you put object in collections and use
contains() for example, you might want to override equals.

In this case (or really always) if you override .equals() for a less
strict check, you *must* also override .hashCode() to be consistent
with that looser .equals(), otherwise some of the standard collections
may behave wrongly with your items.

.



Relevant Pages

  • RE: Equality vs Sameness
    ... > Good call on my misuse of overriding vs overloading. ... So you override Equals and GetHashCode even for forms, ... or wanted to compare two instances of a singleton? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Compare Two Identical Datatable By Content
    ... Even if you override the operators the ... public static bool operator!= ... public override bool Equals(object obj) ... compare the schema. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Comparing Array Objects
    ... > However, on a side-note, when realizing a ValueType class, like a struct ... >> The real reason is that Array doesn't override the Equals method ...
    (microsoft.public.dotnet.framework)
  • Re: Compare two instance of a class
    ... If you override Equal you should also override GetHashCode. ... In most cases I think it is better to implement a specific method to compare ... reference type instances - value comparison is often a business/application ... override default language functionality. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Why use Objectg in Equals method?
    ... superclasses (but not subclasses). ... Of course, if you intend to compare with objects of different classes, ... It is convenient that 'equals(Object o)' is an override - it allows for expressive compactness in a ton of algorithms, e.g., those on which collections classes rely. ...
    (comp.lang.java.programmer)