Morgan Stanley, Morgan Stanley

Source: Internet
Author: User

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 + "]";
}
}

Related Keywords:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.