What java design pattern is appropriate for the situation described below? -


i working on chemistry package , have class lists elements in periodic table. ideally elements part of java enum. unfortunately need 1 more element serve wildcard : every other element should equal element. java not allow override equals() method enums otherwise have done that. able suggest reasonable design pattern situation have described?

edit: thank contributions. indeed failed observe transitive property required equals().

the elements of periodic table assigned different nodes on graph structure(in mathematical sense). given graph structure embeddings of particular subgraph structure in original graph (subgraph isomorphism problem). desired property of subgraph structure have nodes wildcard assigned can map nodes node in original graph regardless of element assigned it. why looking non-transitive relation such wildcard may equal 2 different elements without implying elements equal. current algorithm makes use of generics , calls equals() check if elements in 2 nodes equal.

as mystarrocks pointed out, big problem design violates equals contract. specifically, per spec in class object, equals method should:

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

  • it reflexive: non-null reference value x, x.equals(x) should return true.
  • it symmetric: non-null reference values x , y, x.equals(y) should return true if , if y.equals(x) returns true.
  • it 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.
  • it 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.
  • for non-null reference value x, x.equals(null) should return false.

(source)

your design violate transitive property. if sodium equals wildcard, , wildcard equals potassium, sodium must equal potassium.

a better way create helper equals method when want see if 2 elements can considered equal (which different being equal). wildcard equal wildcard, can considered equal element.

public enum element {   hydrogen,   helium,   sodium,   //.....   uranium,   wild_card;    public boolean consideredequal(object other) {     if (other == null || ! (other instanceof element)) return false;      element e = (element) other;     if (this.equals(element.wild_card) || e.equals(element.wild_card)) return true;     return equals(other);   } } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -