Tuesday, 15 February 2011

java - What is a 'canonical representation' of a field meant to be for equals() method (Joshua Bloch) -



java - What is a 'canonical representation' of a field meant to be for equals() method (Joshua Bloch) -

in chapter 3, item 8:

public final class caseinsensitivestring { private final string s; public caseinsensitivestring(string s) { if (s == null) throw new nullpointerexception(); this.s = s; } @override public boolean equals(object 0) { homecoming o instanceof caseinsensitivestring && ((caseinsensitivestring) o).s.equalsignorecase(s); } // remainder omitted }

after describing issues surrounding equals() method, goes on talk class in context of comparing fields.

for classes, such caseinsensitivestring above, field comparisons more complex simple equality tests. if case, may want store canonical form of field, equals() method can inexpensive exact comparisons on these canonical forms rather more costly inexact comparisons. technique appropriate immutable classes; if object can change, must maintain canonical form up-to-date.

so question (and double-checked 'canonical' means): bloch talking about? canonical form be? i'm ready told reply simple (presumably otherwise editor have told him add together more) want see other people so.

he mentions same thing hashcode() in next item 9.

to give in context, discusses bad version of equals() method caseinsensitivestring:

// broken - violates symmetry @override public boolean equals(object o) { if (o instanceof caseinsensitivestring) homecoming s.equalsignorecase( ((caseinsensitivestring) o).s); if (o instanceof string) // one-way interoperability! homecoming s.equalsignorecase((string) o); homecoming false; }

you should add together final field , store value s.touppercase() it. new field canonical representation s field. new implementation of method equals() (see code bellow) cheaper. approach work immutable classes.

another point should not forget override hashcode() if override equals().

public final class caseinsensitivestring { private final string s; private final string sforequals; //field added simplifier equals method public caseinsensitivestring(string s) { if (s == null) { throw new illegalargumentexception(); //nullpointerexception() - bad practice } this.s = s; this.sforequals = s.touppercase(); } @override public boolean equals(object o) { homecoming o instanceof caseinsensitivestring && ((caseinsensitivestring) o).sforequals.equals(this.sforequals); } @override public int hashcode(){ homecoming sforequals.hashcode(); } // remainder omitted }

java equals

No comments:

Post a Comment