I have following two questions:
1) Why am I getting a NullPointerException
at the line when I am calling t.i.hashCode()
?
2) In what all scenarios is hashCode()
method called and not called? (Does it gets calls only in cases where we are using objects of Hashing related classes?)
o/p is null.
Exception in thread "main" java.lang.NullPointerException at Test.hashCode(EqualsHashcode.java:65) at java.util.Hashtable.put(Unknown Source) at EqualsHashcode.main(EqualsHashcode.java:20)
import java.util.*;
public class EqualsHashcode
{
public static void main(String[] args)
{
//System.out.println("Main Method");
Test s = new Test("bharat",1);
Test p = new Test("bharat",1);
//System.out.println(s);
//System.out.println(p);
//System.out.println(s.equals(p));
Test q = new Test("bharat",2);
//System.out.println(q);
//System.out.println(s.equals(q));
Test r = new Test("bhara",1);
//System.out.println(r);
//System.out.println(s.equals(r));
Hashtable ht = new Hashtable();
ht.put(s,"1");
ht.put(p,"1");
}
}
class Test
{ Test t;
String p;
int i;
Test(String s, int j)
{
p=s;
i=j;
}
public String toString()
{
System.out.println(p+".."+i);
return p+" Hashcode is"+p.hashCode();
}
public boolean equals(Object o)
{
if (this==o)
{
return true;
}
else if ( o instanceof Test)
{
t = (Test) o;
if (this.p.equals(t.p) && this.i==t.i)
return true;
else
return false;
}
else
return false;
}
public int hashCode()
{
System.out.println(t);
System.out.println("Calling hashCode" + " "+ t.p.hashCode()+t.i);
return t.p.hashCode()+t.i;
}
}