Java Collections query -


public class person {     private string name;     public person(string name) { this.name = name; }     public boolean equals(person p) {         return p.name.equals(this.name);     } } 

    statement true?     a. equals method not override object.equals method.     b. compilation fails because private attribute p.name cannot accessed in line 5.     c. work correctly hash-based data structures, class must implement     hashcode method.     d. when adding person objects java.util.set collection, equals method in line 4     prevent duplicates.     answer: 

this question mock exam, preparing ocjp 6 , have doubts option c. says "to work correctly", doesn't imply needing overwrite hashcode? although not overwriting hashcode() work, focusing on word correctly!!!

equals not correctly implemented, takes object, not person parameter.

compilation not fail due private modifier. private access members accessible within entire surrounding class.

this not work correctly hash based data structures, because hashcode() 2 instances , b must equal when a.equals(b) or b.equals(a). default implementation of hashcode based on instance, , not equality of name.

yes, equals(object) method used determine if entries indeed equal in java.util.set; however, if hash based set hashcode() may used short cut determining equality. if hashset() incorrectly implemented, set may decide not call equals(object) afterwards, hashcode()s indicate 2 objects cannot equals.

note proper implementation of hashcode() can definitively determine if object not equals cannot definitively determine if object equals; solely reserved equals(object). hashcode() typically fast call, used discard needed equality checks before actual call equals(object) determine true equality.

note class lacks equals(object) method (but has named equals(person) method not used in equality checks due wrong method signature). such, class not work in set if intent have 1 entry in set per name. however, default implementation of equals(object) in effect, default implementation of hashcode() tailored match, work correctly within set; but, if intent not store same instance twice within set.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -