您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
【第13章:Java类集】_IdentityHashMap类
发布时间:2021-01-03 17:17:51编辑:雪饮阅读()
正常Map操作中key是不可以重复的,若有重复就会有其中一个被覆盖掉。
import java.util.HashMap;
import java.util.Map;
import java.util.Set ;
import java.util.Iterator ;
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(obj==this){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p=(Person)obj;
if(p.name.equals(this.name) && p.age==this.age){
return true;
}
return false;
}
public int hashCode(){
return this.name.hashCode()*this.age;
}
}
public class TestJava{
public static void main(String args[]){
Map<Person,String> map=new HashMap<Person,String>();
map.put(new Person("霞",24),"kasumi");
map.put(new Person("霞",24),"momiji");
Set<Map.Entry<Person,String>> allSet=map.entrySet();
Iterator<Map.Entry<Person,String>> iter=allSet.iterator();
while(iter.hasNext()){
Map.Entry<Person,String> me=iter.next();
System.out.println(me.getKey()+" --> "+me.getValue());
}
}
}
用IdentityHashMap类给Map进行实例化则允许key重复
那么用IdentityHashMap类来实现只需要导入该类然后替换上面的HashMap即可,其它地方都不需要修改,如:
import java.util.IdentityHashMap ;
import java.util.Map;
import java.util.Set ;
import java.util.Iterator ;
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(obj==this){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p=(Person)obj;
if(p.name.equals(this.name) && p.age==this.age){
return true;
}
return false;
}
public int hashCode(){
return this.name.hashCode()*this.age;
}
}
public class TestJava{
public static void main(String args[]){
Map<Person,String> map=new IdentityHashMap<Person,String>();
map.put(new Person("霞",24),"kasumi");
map.put(new Person("霞",24),"momiji");
Set<Map.Entry<Person,String>> allSet=map.entrySet();
Iterator<Map.Entry<Person,String>> iter=allSet.iterator();
while(iter.hasNext()){
Map.Entry<Person,String> me=iter.next();
System.out.println(me.getKey()+" --> "+me.getValue());
}
}
}
D:\>javac TestJava.java
D:\>java TestJava
姓名:霞 年龄:24 --> momiji
姓名:霞 年龄:24 --> kasumi
关键字词:java,IdentityHashMap