SlideShare une entreprise Scribd logo
1  sur  21
MANISH ADLAKHA
   All methods of Object class have explicit general
    contracts because they are meant to be overridden.
   When a class overrides these methods, the contracts
    must be obeyed otherwise the classes dependent on
    these contracts will not function properly.
   Methods of object class
•   equals()
•   hashCode()
•   toString()
•   clone()
•   finalize()
Obey the general contract when overriding
                                  equals
   When a class has a notion of logical equality
    which extends mere object identity
   And the behavior is not by a superclass
   Need to find whether they are logically
    equivalent and not whether they refer to
    same object
   Allows instances to serve as map keys and
    show set behavior
Equivalence relation
 Reflexive – x.equals(x) -> true
 Symmetric –
  x.equals(y) -> true => y.equals(x) -> true
 Transitive
 Consistent -> should return same values
  consistently when equals is called
 For a not-null reference, x.equals(null) ->
  false
   Use the == operator to check if the argument is
    a reference to this object
   Use the instanceof operator to check if the
    argument has the correct type
   Cast the argument to the correct type
   For each significant field in the class, check if
    that field of the argument matches the
    corresponding field of this object
   When you are finished writing, ask yourself three
    questions:
•   Is it symmetric?
•   Is it transitive?
•   Is it consistent?
Always override hashCode when you override
                                   equals
   You must override hashCode in every
    class that overrides equals.

   Failure to do so results in violation of the general
    contract for Object.hashCode, which prevents the class
    from functioning properly in conjunction with all hash-
    based collections, including HashMap, HashSet, and
    Hashtable.
   When invoked on an object more than once, hashCode() must
    consistently return the same integer, provided no information
    used in equals comparisons on the object is modified
   If two objects are equal according to the equals(Object)
    method, then calling the hashCode method on each of the
    two objects must produce the same integer result.
   Not necessary that hashCode() called on two unequal objects
    return distinct hashcode numbers but doing so improves the
    performance of hashtables.
   The key provision that is violated when you fail to override
    hashCode is the second one: equal objects must have equal
    hash codes.
   We may exclude redundant fields from the hashCode
    computation.
   Do not be tempted to exclude significant parts of an object
    from the hash code computation to improve performance.
Always override toString()
   Default return - class name followed by an “at” sign
    (@) and the unsigned hexadecimal representation
    of the hash code, for example,
    “PhoneNumber@163b91
   General contract
    • returned string should be “a concise but informative
      representation that is easy for a person to read”
   providing a good toString() implementation makes your class
    much more pleasant to use.

   toString() invoked when an object is
    ◦ Passed to println() and printf()
    ◦ Used in string concatenation operator or assert
    ◦ Printed by the debugger


   When practical, the toString method should return all of the
    interesting information contained in the object
   Whether or not you decide to specify the format, you should
    clearly document your intentions
   provide programmatic access to all of the information
    contained in the value returned by toString()
Override clone() judiciously
   A flag interface that advertises that an object permits cloning
   Lacks a clone() method
   Object class’ clone() is protected -> so cannot be used
    without using reflection
   Cloneable interface determines the behavior of Object’s
    clone() implementation
   It modifies the behavior of a protected method on a
    superclass
   x.clone() !=x
   x.clone().getclass() == x.getclass()
   x.clone().equals(x) should be true but it is not an
    absolute requirement
   No constructors are to be called when creating a
    clone
   If you override the clone method in a nonfinal class, you
    should return an object obtained by invoking super.clone().
   In practice, a class that implements Cloneable is expected to
    provide a properly functioning public clone method.
   In effect, the clone method should function as another
    constructor; you must ensure that it does no harm to the
    original object and that it properly establishes invariants on
    the clone
   The clone architecture is incompatible with normal use of
    final fields referring to mutable objects
Consider implementing Comparable
   Method of the comparable interface
   Not declared in Object class
   Allows order comparison along with equality comparisons
   Indicates a natural ordering of instances of a class
   sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y
   (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies
    x.compareTo(z) > 0
   x.compareTo(y) == 0 implies that
    sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z
   (x.compareTo(y) == 0) == (x.equals(y)) – Strongly
    recommended but not strictly required
   Violating the compareTo() contract breaks the
    classes dependent on comparison
    ◦ Sorted collections – TreeSet and TreeMap
    ◦ Utility classes collections and Arrays

Contenu connexe

Tendances

Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String ClassVipul Verma
 
Shell sorting
Shell sortingShell sorting
Shell sortingTUC
 
Sorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithmSorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithmDavid Burks-Courses
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using CAshish Gaurkhede
 
13string in c#
13string in c#13string in c#
13string in c#Sireesh K
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationZakaria Hossain
 
Sorting Techniques
Sorting TechniquesSorting Techniques
Sorting TechniquesRafay Farooq
 
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...Umesh Kumar
 
Hash table
Hash tableHash table
Hash tableVu Tran
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
 
Insertion sort
Insertion sortInsertion sort
Insertion sortMYER301
 
Concept of hashing
Concept of hashingConcept of hashing
Concept of hashingRafi Dar
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithmAamir Sohail
 

Tendances (20)

Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String Class
 
Shellshort ppt
Shellshort pptShellshort ppt
Shellshort ppt
 
Binary search
Binary searchBinary search
Binary search
 
Shell sorting
Shell sortingShell sorting
Shell sorting
 
Sorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithmSorting and searching arrays binary search algorithm
Sorting and searching arrays binary search algorithm
 
08 Hash Tables
08 Hash Tables08 Hash Tables
08 Hash Tables
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using C
 
13string in c#
13string in c#13string in c#
13string in c#
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with Animation
 
Sorting Techniques
Sorting TechniquesSorting Techniques
Sorting Techniques
 
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
 
Hash table
Hash tableHash table
Hash table
 
Sorting algorithm
Sorting algorithmSorting algorithm
Sorting algorithm
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Radix final
Radix finalRadix final
Radix final
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Concept of hashing
Concept of hashingConcept of hashing
Concept of hashing
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithm
 

Similaire à Methods common to all objects

Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3Kamal Mukkamala
 
Effective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsEffective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsRoshan Deniyage
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash codemhtspvtltd
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0aravind_aashu
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objectsİbrahim Kürce
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merklebmerkle
 
Object Class
Object ClassObject Class
Object ClassRatnaJava
 
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
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Read carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfRead carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfbharatchawla141
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular ExpressionMasudul Haque
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 

Similaire à Methods common to all objects (20)

Ejp 01
Ejp 01Ejp 01
Ejp 01
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 
Effective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsEffective Java - Methods Common to All Objects
Effective Java - Methods Common to All Objects
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash code
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Collections
CollectionsCollections
Collections
 
Javasession7
Javasession7Javasession7
Javasession7
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
 
Object Class
Object ClassObject Class
Object Class
 
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
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Read carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfRead carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdf
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 

Plus de Sandeep Chawla

Plus de Sandeep Chawla (6)

Exception
ExceptionException
Exception
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Sandeep Chawla Visual Resume
Sandeep Chawla Visual ResumeSandeep Chawla Visual Resume
Sandeep Chawla Visual Resume
 

Dernier

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Dernier (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Methods common to all objects

  • 2. All methods of Object class have explicit general contracts because they are meant to be overridden.  When a class overrides these methods, the contracts must be obeyed otherwise the classes dependent on these contracts will not function properly.  Methods of object class • equals() • hashCode() • toString() • clone() • finalize()
  • 3. Obey the general contract when overriding equals
  • 4. When a class has a notion of logical equality which extends mere object identity  And the behavior is not by a superclass  Need to find whether they are logically equivalent and not whether they refer to same object  Allows instances to serve as map keys and show set behavior
  • 5. Equivalence relation  Reflexive – x.equals(x) -> true  Symmetric – x.equals(y) -> true => y.equals(x) -> true  Transitive  Consistent -> should return same values consistently when equals is called  For a not-null reference, x.equals(null) -> false
  • 6. Use the == operator to check if the argument is a reference to this object  Use the instanceof operator to check if the argument has the correct type  Cast the argument to the correct type  For each significant field in the class, check if that field of the argument matches the corresponding field of this object  When you are finished writing, ask yourself three questions: • Is it symmetric? • Is it transitive? • Is it consistent?
  • 7. Always override hashCode when you override equals
  • 8. You must override hashCode in every class that overrides equals.  Failure to do so results in violation of the general contract for Object.hashCode, which prevents the class from functioning properly in conjunction with all hash- based collections, including HashMap, HashSet, and Hashtable.
  • 9. When invoked on an object more than once, hashCode() must consistently return the same integer, provided no information used in equals comparisons on the object is modified  If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.  Not necessary that hashCode() called on two unequal objects return distinct hashcode numbers but doing so improves the performance of hashtables.
  • 10. The key provision that is violated when you fail to override hashCode is the second one: equal objects must have equal hash codes.  We may exclude redundant fields from the hashCode computation.  Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance.
  • 12. Default return - class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example, “PhoneNumber@163b91  General contract • returned string should be “a concise but informative representation that is easy for a person to read”
  • 13. providing a good toString() implementation makes your class much more pleasant to use.  toString() invoked when an object is ◦ Passed to println() and printf() ◦ Used in string concatenation operator or assert ◦ Printed by the debugger  When practical, the toString method should return all of the interesting information contained in the object  Whether or not you decide to specify the format, you should clearly document your intentions  provide programmatic access to all of the information contained in the value returned by toString()
  • 15. A flag interface that advertises that an object permits cloning  Lacks a clone() method  Object class’ clone() is protected -> so cannot be used without using reflection  Cloneable interface determines the behavior of Object’s clone() implementation  It modifies the behavior of a protected method on a superclass
  • 16. x.clone() !=x  x.clone().getclass() == x.getclass()  x.clone().equals(x) should be true but it is not an absolute requirement  No constructors are to be called when creating a clone
  • 17. If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone().  In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method.  In effect, the clone method should function as another constructor; you must ensure that it does no harm to the original object and that it properly establishes invariants on the clone  The clone architecture is incompatible with normal use of final fields referring to mutable objects
  • 19. Method of the comparable interface  Not declared in Object class  Allows order comparison along with equality comparisons  Indicates a natural ordering of instances of a class
  • 20. sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y  (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0  x.compareTo(y) == 0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z  (x.compareTo(y) == 0) == (x.equals(y)) – Strongly recommended but not strictly required
  • 21. Violating the compareTo() contract breaks the classes dependent on comparison ◦ Sorted collections – TreeSet and TreeMap ◦ Utility classes collections and Arrays