java - Implementing meaningful equals method for non-static inner classes -


this question has answer here:

i wondering if there way of implementing equals method non-static inner class in java. class foo inner-class bar this:

public class foo {    private final string foo; // constructor omitted    public /* non-static */ class bar {      private final string bar; // constructor omitted      @override     public boolean equals(object other) {       return other != null && other.getclass() == getclass()         && ((bar) other).bar.equals(this.bar)         && foo.this.equals(foo.((bar) other)); // will, of course, not compile.     }   }    @override   public boolean equals(object other) {     return other != null && other.getclass() == getclass()       && ((foo) other).foo.equals(foo);   } } 

my classes lot more complex in reality , want reuse foo#equals method within bar#equals in order save me lot of code. considering make "inner-class-relationship" explicit in order being able refer "outer" class. however, have add accessor methods manually , want avoid this. cannot rid of feeling there should java approach of doing this.

yes, possible. done when need pass around "key" objects represent unique identifier set of data not either have data or want transport it.

class somedata {     private string data;     public static class key {         private final int firstid;         private final int secondid;           public key(int firstid, int secondid) {             this.firstid = firstid;             this.secondid = secondid;         }          public boolean equals(object x) {             if(!(x instanceof key))                 return false;             key key = ((key)x);              return this.firstid == key.firstid              && this.secondid == key.secondid;          }          // implement hashcode     } } 

in example above inner class static doesn't matter. reason set way exterior classes construct it. make sure when overriding .equals .hashcode. should change each other.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -