您的位置:首页 > 编程语言 > Java开发

【Java类集】_IdentityHashMap类笔记

2014-10-01 23:10 281 查看


【Java类集】_IdentityHashMap类笔记

分类: Java

【Java类集】_IdentityHashMap类笔记

在正常的Map操作,key本身是不能够重复的。

[java] view
plaincopyprint?

import java.util.Map;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Set;

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;

}

public boolean equals(Object obj){

if(this==obj){

return true;

}

if(!(obj instanceof Person)){

return false;

}

Person per = (Person) obj;

if(this.name.equals(per.name)&&this.age==per.age){

return true;

}else{

return false;

}

}

public int hashCode(){

return this.name.hashCode()*this.age;

}

}

public class HashMapDemo08{

public static void main(String args[]){

Map<Person,String> map = null;

map = new HashMap<Person,String>();

map.put(new Person("张三",30),"zhangsan_1");//增加内容

map.put(new Person("张三",30),"zhangsan_2");//增加内容

map.put(new Person("李四",31),"lisi");//增加内容

Set<Map.Entry<Person,String>> allSet = null;

allSet = map.entrySet();

Iterator<Map.Entry<Person,String>> iter=null;

iter = allSet.iterator();

while(iter.hasNext()){

Map.Entry<Person,String> me = iter.next();

System.out.println(me.getKey()+"-->"+me.getValue());

}

}

}

输出:

姓名:李四;年龄:31-->lisi

姓名:张三;年龄:30-->zhangsan_2

使用HashMap操作的时候,key 内容是不能重复的,如果现在希望key内容可以重复(指的重复是指两个对象的地址不一样key1==key2)则要使用IdentityHashMap类。

[java] view
plaincopyprint?

import java.util.Map;

import java.util.IdentityHashMap;

import java.util.Iterator;

import java.util.Set;

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;

}

public boolean equals(Object obj){

if(this==obj){

return true;

}

if(!(obj instanceof Person)){

return false;

}

Person per = (Person) obj;

if(this.name.equals(per.name)&&this.age==per.age){

return true;

}else{

return false;

}

}

public int hashCode(){

return this.name.hashCode()*this.age;

}

}

public class IdentityHashMapDemo01{

public static void main(String args[]){

Map<Person,String> map = null;

map = new IdentityHashMap<Person,String>();

map.put(new Person("张三",30),"zhangsan_1");//增加内容

map.put(new Person("张三",30),"zhangsan_2");//增加内容

map.put(new Person("李四",31),"lisi");//增加内容

Set<Map.Entry<Person,String>> allSet = null;

allSet = map.entrySet();

Iterator<Map.Entry<Person,String>> iter=null;

iter = allSet.iterator();

while(iter.hasNext()){

Map.Entry<Person,String> me = iter.next();

System.out.println(me.getKey()+"-->"+me.getValue());

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: