Other than immutable value objects, when should I override `equals ()`?

It is clear that equals()(and, of course, hashCode()) are valuable when you are dealing with objects of constant value - map keys, strongly typed field values ​​that need to be compared between objects that contain them, etc.

But besides value objects, how often is it very likely that you will have two independently constructed instances and want them to be equal?

It’s hard for me to imagine a realistic scenario where relational equality would not be de facto, you will get what you want; and in these specific cases, it seems that the equivalent scenario method ( isEquivalentTo(Foo)rather than equals(Object)) will be safer. In particular, for mutable objects?

What is the precedent for equals()non-valuable types?

+3
source share
2 answers

Um. Set<E>is mutable and has a (useful) definition equals(). It does not seem useless ...

0
source

From docs.oracle.com :

List of Interfaces <E>

boolean contains (Object o)

Returns true if this list contains the specified element. 

More formally returns true if and only if this list contains at least one element e such that (o == null? E == null: o.equals (e) ).

So redefinition equalsis useful for these (and other) language constructs.

Consider this (sorry, this is in C #):

class MimeType
{
    public string Name { get; set; }
    public string Extension { get; set; }    

    public override bool Equals(object obj)
    {
        var other = obj as MimeType;
        if (other == null) return false;
        return other.Name == Name;
    }
}

class Program
{
    void Main()
    {
        var jpeg1 = new MimeType();
        jpeg1.Name = "image/jpeg";
        jpeg1.Extension = ".jpg";

        var jpeg2 = new MimeType();
        jpeg2.Name = "image/jpeg";
        jpeg2.Extension = ".jpeg";    

        var list = new List<MimeType>();
        list.Add(jpeg1);

        if (!list.Contains(jpeg2))
            list.Add(jpeg2);
    }
}

jpeg2 , .

Update:

Extension MimeType.

0

All Articles