SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
Rahul Jamwal
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String Class
Vipul Verma
 
Shellshort ppt
Shellshort pptShellshort ppt
Shellshort ppt
hannatamayao
 
Binary search
Binary searchBinary search
Binary search
AparnaKumari31
 
Shell sorting
Shell sortingShell sorting
Shell sorting
TUC
 
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
David Burks-Courses
 
08 Hash Tables
08 Hash Tables08 Hash Tables
08 Hash Tables
Andres Mendez-Vazquez
 
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
Ashish 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 Animation
Zakaria Hossain
 
Sorting Techniques
Sorting TechniquesSorting Techniques
Sorting Techniques
Rafay 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 table
Vu Tran
 
Sorting algorithm
Sorting algorithmSorting algorithm
Sorting algorithm
Balaji Nangare
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
Kaushal Shah
 
Radix final
Radix finalRadix final
Radix final
hannatamayao
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
Dabbal Singh Mahara
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
MYER301
 
Concept of hashing
Concept of hashingConcept of hashing
Concept of hashing
Rafi 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 algorithm
Aamir Sohail
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
Rahul Jamwal
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String Class
Vipul Verma
 
Shell sorting
Shell sortingShell sorting
Shell sorting
TUC
 
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
David 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 C
Ashish 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 Animation
Zakaria Hossain
 
Sorting Techniques
Sorting TechniquesSorting Techniques
Sorting Techniques
Rafay 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 table
Vu Tran
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
Kaushal Shah
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
MYER301
 
Concept of hashing
Concept of hashingConcept of hashing
Concept of hashing
Rafi 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 algorithm
Aamir Sohail
 

Similar to Methods common to all objects (20)

Ejp 01
Ejp 01Ejp 01
Ejp 01
Md. Fasihul Kabir
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
Kamal 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 Objects
Roshan Deniyage
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash code
mhtspvtltd
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
FaRaz Ahmad
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
aravind_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
 
Collections
CollectionsCollections
Collections
sagsharma
 
Javasession7
Javasession7Javasession7
Javasession7
Rajeev Kumar
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
bmerkle
 
Object Class
Object ClassObject Class
Object Class
RatnaJava
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
Mumbai Academisc
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Generics collections
Generics collectionsGenerics collections
Generics collections
Yaswanth Babu Gummadivelli
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus 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.pdf
bharatchawla141
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
Masudul Haque
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
phanleson
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
Kamal 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 Objects
Roshan Deniyage
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash code
mhtspvtltd
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
FaRaz Ahmad
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
aravind_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 Merkle
bmerkle
 
Object Class
Object ClassObject Class
Object Class
RatnaJava
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus 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.pdf
bharatchawla141
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
Masudul Haque
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
phanleson
 
Ad

More from Sandeep Chawla (6)

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

Recently uploaded (20)

#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 

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