Question

(JAVA) B. How should objects be compared for equality? Why?

(JAVA) B. How should objects be compared for equality? Why?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Comparing objects with equals() :-

We use the equals() method to compare objects in Java. In order to determine if two objects are the same, equals() compares the values of the objects

the == operator and equals() method may appear to do the same thing, but in truth they work differently. The == operator compares whether two object references point to the same object.

Example :-System.out.println(exampl1.equals(example2));

Comparing objects with hashcode() :-

We use the hashcode() method to optimize performance when comparing objects. Executing hashcode() returns a unique ID for each object in your program, which makes the task of comparing the whole state of the object much easier.

If an object’s hashcode is not the same as another object’s hashcode, there is no reason to execute the equals() method: you just know the two objects are not the same. On the other hand, if the hashcode is the same, then you must execute the equals() method to determine whether the values and fields are the same

Method Overriding is a technique where the behavior of the parent class or interface is written again overridden in the subclass in order to take advantage of Polymorphism. Every Object in Java includes an equals() and a hashcode() method, but they must be overridden to work properly.

Add a comment
Know the answer?
Add Answer to:
(JAVA) B. How should objects be compared for equality? Why?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT