Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement equals method for Java anonymous class properly?
    primarykey
    data
    text
    <p>In <a href="https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java/13299709#13299709">this</a> post I suggested a solution that uses interface and anonymous class. However, there is one thing to be implemented: the <code>hashCode</code> and <code>equals</code> method.</p> <p>However I found it is hard to implement <code>equals</code> for anonymous class that implements an interface. In that example the interface is <code>Pair&lt;L,R&gt;</code>, and a factory method <code>Pairs.makePair</code> will return an anonymous implementation for it. Suppose I added an <code>equals</code> implementation. The user may implement their own <code>Pair&lt;L,R&gt;</code> classes with a different <code>equals</code> code, therefore the call <code>userobj.equals(makepairobj)</code> will enter their code, and <code>makepairobj.equals(userobj)</code> will enter my code. Because I have no control of their code, it is hard to make sure <code>equals</code> to be symmetric, which is required for a good implementation.</p> <p>I believe this problem is common for other cases, so I would like to know how this issue being address generally?</p> <p>EDIT: In typical class, the implementation of <code>equals</code> will check the parameter type to make sure it is the same as its own. This guarantee only the implementing code will be called to compare the objects. However, the anonymous class do not have a name and cannot check the type with <code>instanceof</code>. What I can do is make sure it is an instance of the implementing interface/class. Which is not enough to prevent the above scenario. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload