Amazon Interview Question
InternsTeam: Web Service
Country: United States
Interview Type: Phone Interview
I wasn't sure if there would be a null pointer exception at runtime, so I put it into eclipse. New here, but I had to change a bit of the code to get it to compile and run. Here's the code I ran, the output was
success
null
So my initial assumption about a null pointer exception was wrong.
import java.util.*;
class Test {
public int i=0;
@Override
public int hashCode() {
return i;
}
}
class HashPractice{
public static void main(String[] args){
HashMap <Test, String> hm = new HashMap<Test, String>();
Test t1 = new Test();
hm.put(t1,"success");
System.out.println(hm.get(t1)); //print success
t1.i = 10;
System.out.println(hm.get(t1)); //NULL
}
}
I think you're missing the core concept of this question.Focus not on syntax. Rather focus on the fundamentals of hashing.
I think the result you said is correct.
But I run this code in eclipse, I found the result is two lines of "success".
Why is that?
Here the Key(of HashMap) is object itself not the value of i of that object.
So the statement "t1.i = 10;" is not changing the object it just assigning value to data member.
Finallu the output is "Success"
As output is success and null because of first time hashcode is 0; and we insert value in
- Rohit March 07, 2013bucket '0' but second time hashcode is 10 and bucket 10 does not have any value.