zoukankan      html  css  js  c++  java
  • 可以重复的Map: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()) ;
      }
     }
    };

    程序运行结果:

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

    姓名:张三;年龄:30-->zhangsan_2  //根据程序运行结果可以发现,重复的key的内容将前面第一个key的内容给覆盖了

    只要地址不相等(key1!=key2),就可以利用IdentityHashMap来实现将不重复地址的key,但是内容是一样的key添加到集合中去。

    对象内容一样但是地址不同,这是由于在实例化的过程中都是用new这个关键字(每次使用new这个关键字,vm都会给其分配一个内存空间),所以可以实现地址不同但是内容

  • 相关阅读:
    设计模式的读书笔记
    腾讯历年笔试题
    原始套接字的简单tcp包嗅探
    一些有意思,有深度,容易错的代码收集
    sizeof的用法的一些归纳
    一道有趣的题目
    C++的一些设计注意点
    Gazebo Ros入门
    机器学习之多变量线性回归(Linear Regression with multiple variables)
    机器学习之单变量线性回归(Linear Regression with One Variable)
  • 原文地址:https://www.cnblogs.com/dqiii/p/13161313.html
Copyright © 2011-2022 走看看