SlideShare una empresa de Scribd logo
1 de 33
Effective Java Presentation – 01
Method Common to All Objects (ch – 03)
By Md. Fasihul Kabir
Content Overview
 Obey the general contract when overriding equals
(Item 8)
 Always override hashCode when you override
equals (Item 9)
 Always override toString (Item 10)
 Override clone judiciously (Item 11)
 Consider implementing comparable (Item 12)
Obey the general contract when
overriding equals
Best Approach – Avoid! Works if
 Each instance of a class is unique
 You don’t care if class has logical equality
 The superclass equals is satisfactory
 Class is not public and equals method never will be
invoked
Best Approach – Avoid! Works if
 Each instance of a class is unique
 You don’t care if class has logical equality
 The superclass equals is satisfactory
 Class is not public and equals method never will be
invoked
General Contract for equals
 Reflexive
 x.equals(x) must return true
 Symmetric
 x.equals(y) iff y.equals(x)
 Transitive
 x.equals(y) && y.equals(z)
 Then x.equals(z)
 Consistency
 Null values
 x.equals(null) must return false
Symmetry
Symmetry (Cont.)
x equals to y ::
true
y equals to x ::
false
Symmetry (Cont.)
x equals to y ::
true
y equals to x ::
false
Symmetry (Cont.)
How to Implement equals()
 Use == to see if argument is a reference to this
object
 Use instanceof to check if argument is of the correct
type
 Cast the argument to the correct type
 Check each “significant field”
 Check symmetric, transitive, consistent
What to Do
 Always override hashCode when override equals
 Don’t substitute another type for Object
 Don’t throw NullPointerException or
ClassCastException
Always override hashCode when
you override equals
Contract
 hashCode() must return same interger on different
calls, as long as equals() unchanged
 If x.equals(y) is true, then x, y must have same
hashcode
 It is not required that unequal objects have different
hashcodes
Avoiding hashCode
Avoiding hashCode (Contd.)
Simple hashCode Implementation
Simple Recipe
 Start with some nonzero value
 Say, result = 17;
 (Repeatedly) compute in hashCode “c” for each
“significant field”
 Apply various rules for each data type
 Combine
 result = result*37 + c;
Optimize hashCode() for immutable
objects
Always override toString
 “It is recommended that all subclasses override this
method.” Good advice, indeed!
 Providing a good toString implementation makes
your class much more pleasant to use
 Return all of the interesting information contained in
the object
 Clearly document your intentions
 Provide getters for values toString() provides
Override clone judiciously
Contract
 x.clone() != x
 x.clone().getClass() = x.getClass()
 x.clone().equals(x) will be true
 No constructors are called
The role of mutability
 If a class has only primitive fields or immutable
references as fields, super.clone() returns exactly
what you want
 For objects with mutable references, “deep copies”
are required
Cloning Problems
 Cloning may be a problem with final fields
 Cloning recursively may not be sufficient
Other Mechanism
 Better off not implementing Cloneable
 Provide a separate copy mechanism
 Copy Constructor:
 public ClassA ( ClassA a )
 Factory
 public static ClassA newInstance ( ClassA a )
Consider implementating
comparable
Contract
 x.compareTo(y) = - y.compareTo(x)
 If x.compareTo(y)>0 && y.compareTo(z)>0, then
x.compareTo(z) must be greater than 0
 If x.compareTo(y)==0, then
sign(x.compareTo(z))==sign(y.compareTo(z))
 It is strongly recommended, but not strictly required
that
(x.compareTo(y)==0) == (x.equals(y))
Inconsistent with equals
Inconsistent with equals (Cont.)
x.equals(y) :: false
x.compareTo(y) :: 0
Inconsistent with equals (Cont.)
Inconsistent with equals (Cont.)
Size of Set s :: 2
Size of Set h :: 1
 Thanks 

Más contenido relacionado

Similar a Ejp 01

findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merklebmerkle
 
25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.pptPiyushAery
 
information on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptinformation on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptssuserf170c4
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Empatika
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSSuraj Kumar
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsMICHRAFY MUSTAFA
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0aravind_aashu
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Leonardo Borges
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningExcel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningPrantikMaity6
 

Similar a Ejp 01 (20)

findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
 
Collections
CollectionsCollections
Collections
 
25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt
 
information on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.pptinformation on -inheritance-polymorphism in java.ppt
information on -inheritance-polymorphism in java.ppt
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
core java
 core java core java
core java
 
Built-in Classes in JAVA
Built-in Classes in JAVABuilt-in Classes in JAVA
Built-in Classes in JAVA
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA LearningExcel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
Excel 2016 VBA PPT Slide Deck - For Basic to Adavance VBA Learning
 

Ejp 01

  • 1. Effective Java Presentation – 01 Method Common to All Objects (ch – 03) By Md. Fasihul Kabir
  • 2. Content Overview  Obey the general contract when overriding equals (Item 8)  Always override hashCode when you override equals (Item 9)  Always override toString (Item 10)  Override clone judiciously (Item 11)  Consider implementing comparable (Item 12)
  • 3. Obey the general contract when overriding equals
  • 4. Best Approach – Avoid! Works if  Each instance of a class is unique  You don’t care if class has logical equality  The superclass equals is satisfactory  Class is not public and equals method never will be invoked
  • 5. Best Approach – Avoid! Works if  Each instance of a class is unique  You don’t care if class has logical equality  The superclass equals is satisfactory  Class is not public and equals method never will be invoked
  • 6. General Contract for equals  Reflexive  x.equals(x) must return true  Symmetric  x.equals(y) iff y.equals(x)  Transitive  x.equals(y) && y.equals(z)  Then x.equals(z)  Consistency  Null values  x.equals(null) must return false
  • 8. Symmetry (Cont.) x equals to y :: true y equals to x :: false
  • 9. Symmetry (Cont.) x equals to y :: true y equals to x :: false
  • 11. How to Implement equals()  Use == to see if argument is a reference to this object  Use instanceof to check if argument is of the correct type  Cast the argument to the correct type  Check each “significant field”  Check symmetric, transitive, consistent
  • 12. What to Do  Always override hashCode when override equals  Don’t substitute another type for Object  Don’t throw NullPointerException or ClassCastException
  • 13. Always override hashCode when you override equals
  • 14. Contract  hashCode() must return same interger on different calls, as long as equals() unchanged  If x.equals(y) is true, then x, y must have same hashcode  It is not required that unequal objects have different hashcodes
  • 18. Simple Recipe  Start with some nonzero value  Say, result = 17;  (Repeatedly) compute in hashCode “c” for each “significant field”  Apply various rules for each data type  Combine  result = result*37 + c;
  • 19. Optimize hashCode() for immutable objects
  • 21.  “It is recommended that all subclasses override this method.” Good advice, indeed!  Providing a good toString implementation makes your class much more pleasant to use  Return all of the interesting information contained in the object  Clearly document your intentions  Provide getters for values toString() provides
  • 23. Contract  x.clone() != x  x.clone().getClass() = x.getClass()  x.clone().equals(x) will be true  No constructors are called
  • 24. The role of mutability  If a class has only primitive fields or immutable references as fields, super.clone() returns exactly what you want  For objects with mutable references, “deep copies” are required
  • 25. Cloning Problems  Cloning may be a problem with final fields  Cloning recursively may not be sufficient
  • 26. Other Mechanism  Better off not implementing Cloneable  Provide a separate copy mechanism  Copy Constructor:  public ClassA ( ClassA a )  Factory  public static ClassA newInstance ( ClassA a )
  • 28. Contract  x.compareTo(y) = - y.compareTo(x)  If x.compareTo(y)>0 && y.compareTo(z)>0, then x.compareTo(z) must be greater than 0  If x.compareTo(y)==0, then sign(x.compareTo(z))==sign(y.compareTo(z))  It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))
  • 30. Inconsistent with equals (Cont.) x.equals(y) :: false x.compareTo(y) :: 0
  • 32. Inconsistent with equals (Cont.) Size of Set s :: 2 Size of Set h :: 1

Notas del editor

  1. # This is true for classes such as Thread that represent active entities rather than values.# For example, java.util.Random could have overridden equals to check whether two Random instances would produce the same sequence of random numbers going forward, but the designers didn’t think that clients would need or want this functionality. # For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.@
  2. # This is true for classes such as Thread that represent active entities rather than values.# For example, java.util.Random could have overridden equals to check whether two Random instances would produce the same sequence of random numbers going forward, but the designers didn’t think that clients would need or want this functionality. # For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.
  3. # This is just a performance optimization
  4. Notice that two PhoneNumber instances are involved: one is used for insertion into the HashMap, and a second, equal, instance is used for (attempted) retrieval. The PhoneNumber class’s failure to override hashCode causes the two equal instances to have unequal hash codes, in violation of the hashCode contract. Therefore the get method is likely to look for the phone number in a different hash bucket from the one in which it was stored by the put method. Even if the two instances happen to hash to the same bucket, the get method will almost certainly return null, as HashMap has an optimization that caches the hash code associated with each entry and doesn’t bother checking for object equality if the hash codes don’t match.
  5. # It’s legal because it ensures that equal objects have the same hash code. It’s atrocious because it ensures that every object has the same hash code. Therefore, every object hashes to the same bucket, and hash tables degenerate to linked lists. Programs that should run in linear time instead run in quadratic time. For large hash tables, this is the difference between working and not working.