Morgan Stanley, Morgan Stanley
Morgan Stanley-September 8, 2016 interview questions:
Given a Map <Person, Object> map = new HashMap <Person, Object> ();
Put two persons. If the IDs are the same, the two persons are determined to be the same.
Then modify the id and then determine.
Package cn. itcast. test;
Import java. util. HashMap;
Import java. util. Map;
Public class TestHashMap {
Public static void main (String [] args ){
Map <Person, Object> map = new HashMap <Person, Object> ();
Person p1 = new Person (1, "aaa ");
Person p2 = new Person (1, "bbb ");
Map. put (p1, p1 );
Map. put (p2, p2 );
System. out. println (map. get (p1 ));// Person [id = 1, name = bbb]
System. out. println (map. get (p2 ));// Person [id = 1, name = bbb]
P2.setId (2 );
System. out. println (map. get (p1 ));// Person [id = 2, name = bbb]
System. out. println (map. get (p2 ));// Null
}
}
Class Person {
Private int id;
Private String name;
Public int getId (){
Return id;
}
Public Person (int id, String name ){
Super ();
This. id = id;
This. name = name;
}
Public void setId (int id ){
This. id = id;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
@ Override
Public int hashCode (){// Pay attention here
Return id;
}
@ Override
Public boolean equals (Object obj ){// Pay attention here
If (id = (Person) obj). getId ()){
Return true;
}
Return false;
}
@ Override
Public String toString (){
Return "Person [id =" + id + ", name =" + name + "]";
}
}