Note that there are some explanatory texts on larger screens.

plurals
  1. POhashcode() and equals() method
    text
    copied!<p>so i have a question on hashcode() and equals() method</p> <p>Let's say I just write a very basic program overridng both the methodes</p> <pre><code>import java.util.*; class Employee { private String name; private int empid; public Employee(String name,int empid) { this.name=name; this.empid=empid; } public int getEmpid() { return empid; } public String getName() { return name; } public boolean equals(Object obj) { System.out.println("equals has just been called..."); Employee e1=(Employee)obj; return ((name.equals(e1.name)) &amp;&amp; (empid==e1.empid)); } public int hashCode() { System.out.println("hashcode called..."); return empid; } } </code></pre> <p>Then, let's say I write another class to add and iterate the elements in HashSet</p> <pre><code>class Five { public static void main(String args[]) { HashSet hs1=new HashSet(); hs1.add(new Employee("Alex",25)); hs1.add(new Employee("Peter",25)); hs1.add(new Employee("Martin",25)); hs1.add(new Employee("Alex",25)); Iterator itr=hs1.iterator(); while(itr.hasNext()) { Employee e=(Employee)itr.next(); System.out.println(e.getEmpid()+"\t"+e.getName()); } } } </code></pre> <p>now the question is when i try to add Alex again with the same empid the equals() always called thee times</p> <p>as there is no index n hashmap so in case if it first be checked with previously added Alex it will return true and should not be called for the other two elements (peter and martin) but equals always called 3 times</p> <p>why..??</p> <p>is objects within same bucket do also have the index..??</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload