Note that there are some explanatory texts on larger screens.

plurals
  1. POHash code implementation in java
    primarykey
    data
    text
    <pre><code>package MavenWeb.MavenWeb; import java.util.HashMap; import java.util.Map; public class StringEquality { public static void main(String[] args) { Person p1 = new Person("Naveen", 22, 1000); Person p2 = new Person("Naveen", 21, 2000); Person p3 = new Person("Naveen", 23, 3000); if(p1.equals(p2)){ System.out.println("P1 and p2 :" + p1.equals(p2)); } else{ System.out.println("P1 and p2 :" + p1.equals(p2)); } if(p1.equals(p3)){ System.out.println("P1 and p3 :" + p1.equals(p3)); } Map&lt;Person, Object&gt; map = new HashMap&lt;Person, Object&gt;(); map.put(p1, p1); map.put(p2, p2); System.out.println(map.get(new Person("Naveen", 21, 2000))); } } </code></pre> <p>...</p> <pre><code>class Person{ public Person(String name, int id, float salary){ this.name = name; this.id = id; this.salary = salary; } public Float getSalary() { return salary; } public void setSalary(Float salary) { this.salary = salary; } String name; Float salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } int id; @Override public boolean equals(Object obj) { if(obj == null){ return false; } if(this == obj){ return true; } if(obj instanceof Person){ Person person = (Person)obj; if((person.getName().equals(name)) &amp;&amp; person.getId() == id &amp;&amp; person.getSalary() == salary){ return true; } } return false; } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + name.hashCode(); hashCode = 31 * hashCode + id; hashCode = 31 * hashCode + salary.intValue(); return hashCode; } @Override public String toString() { return "Name :" + name + ", id : " + id; } } </code></pre> <p>I have write the following program. Little bit confused regarding hashcode implementation,</p> <ol> <li>Why we use 31 in implementation</li> <li>According to equals method logic this program should return p2(Naveen, 21) instance but it is returning null. why?</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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