java - creating a polymorphic equals expression -


my question concerns altering expression in java make polymorphic. class called cshash , used create hash-tables given datatype dt, , given keytype kt. now, in several methods within class (delete, search, insert, etc.) method uses equals function that, in non-polymorphic version, uses string ( key in non-polymorphic version of type string). thinking create equals method written along lines of following code. question is... valid means of testing equality?

public boolean equals(object x) {     string i;     = new string[1];          string y;     y = new string[1];     == + this;              // use + operator add 'this' object     y == y + (findkey(other))x; // same other object. findkey methods returns kt given object, use return typecast object x.     int j = i.compareto(y);     // use built in string compare method      if(j = 0) {return true;}    // use if else determine if equal     else {return false;} } 

i start reading spec:

indicates whether other object "equal to" one.

the equals method implements equivalence relation on non-null object references:

it reflexive: non-null reference value x, x.equals(x) should return true. symmetric: non-null reference values x , y, x.equals(y) should return true if , if y.equals(x) returns true. transitive: non-null reference values x, y, , z, if x.equals(y) returns true , y.equals(z) returns true, x.equals(z) should return true. consistent: non-null reference values x , y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on objects modified. non-null reference value x, x.equals(null) should return false. equals method class object implements discriminating possible equivalence relation on objects; is, non-null reference values x , y, method returns true if , if x , y refer same object (x == y has value true).

note necessary override hashcode method whenever method overridden, maintain general contract hashcode method, states equal objects must have equal hash codes.

in other words, long given 3 objects x, y, , z following hold:

x.equals(y) implies y.equals(x) !x.equals(y) implies !y.equals(x) x == y implies x.equals(y) x.equals(y) && y.equals(z) implies x.equals(z) 

if equals method follows contract, valid java object.equals implementation. can create lots , lots of unit tests quite ensure corner cases covered.

note have override hashcode related behavior.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -