首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

HasnMap运用非系统类作为key

2012-12-23 
HasnMap使用非系统类作为key1 key类覆写equals hashCode 方法package collectionTestimport java.util.Ha

HasnMap使用非系统类作为key

1 key类覆写equals hashCode 方法

package collectionTest;import java.util.HashMap;import java.util.Map;class Person{private String name ;private int age ;public Person(String name,int age){this.name = name ;this.age = age ;}public String toString(){return "姓名:" + this.name + ";年龄:" + this.age ;}@Overridepublic boolean equals(Object obj) {if (this == obj){return true;}if (!(obj instanceof Person)){return false;}Person that = (Person)obj;if (this.name.equals(that.name) && this.age == that.age){return true;}return false;}@Overridepublic int hashCode() {return this.name.hashCode() * this.age;}};public class MapKeyTest {public static void main(String[] args) {Map<Person,String> map = new HashMap<Person,String>() ;map.put(new Person("张三",30),"zhangsan");// 增加内容System.out.println(map.get(new Person("张三",30))) ;}}
?

热点排行