Java类集 _IdentityHashMap 类

来源:互联网 发布:学陶笛的app软件 编辑:程序博客网 时间:2024/05/16 00:53

了解IdentityHashMap 类的作用

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

import java.util.IdentityHashMap ;import java.util.HashMap ;import java.util.Set ;import java.util.Iterator ;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 boolean equals(Object obj){if(this==obj){return true ;}if(!(obj instanceof Person)){return false ;}Person p = (Person)obj ;if(this.name.equals(p.name)&&this.age==p.age){return true ;}else{return false ;}}public int hashCode(){return this.name.hashCode() * this.age ;}public String toString(){return "姓名:" + this.name + ",年龄:" + this.age ;}};public class IdentityHashMapDemo01{public static void main(String args[]){Map<Person,String> map = null ;// 声明Map对象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 ;// 准备使用Set接收全部内容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()) ;}}
使用HashMap 操作的时候,key 内容是不能重复的。如果现在希望 key 的内容可以重复(指的重复是指两个对象的地址不一样 key1==key2)则要使用 IdentityHashMap 类。

import java.util.IdentityHashMap ;import java.util.Set ;import java.util.Iterator ;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 boolean equals(Object obj){if(this==obj){return true ;}if(!(obj instanceof Person)){return false ;}Person p = (Person)obj ;if(this.name.equals(p.name)&&this.age==p.age){return true ;}else{return false ;}}public int hashCode(){return this.name.hashCode() * this.age ;}public String toString(){return "姓名:" + this.name + ",年龄:" + this.age ;}};public class IdentityHashMapDemo02{public static void main(String args[]){Map<Person,String> map = null ;// 声明Map对象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 ;// 准备使用Set接收全部内容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()) ;}}};
就算是两个对象的内容相等,但是因为都使用了 new 关键字,所以地址肯定不等,那么就可以加入进去, key 是可以重复的。

总结:

1、了解一下IdentityHashMap 类的作用即可,在实际中此类实际上是使用的非常少的。


原创粉丝点击