为什么我的hashmap会覆盖最后一个值?

时间:2014-02-09 06:13:14

标签: java hashmap

我对我的项目感到震惊......必须维护lang数组的大型hashmap ....我尝试使用示例,但它无法工作....我不能将键存储在数组中....感谢预先...

class K{
  int key;
}

class V{
  int data;
}

class hashmp{
  public static void main(String args[]){
       HashMap<K,V> hm=new HashMap<K,V>();
       K key1=new K();
       for(int i=0;i<5;i++){    
         V val=new V();
         key1.key=i;
         val.data=i+5;
         hm.put(key1,val);
       }
       System.out.println();
       for(int i=0;i<5;i++){
         key1.key=i;
         V pt=hm.get(key1);
         System.out.println("\n"+hm.containsKey(key1)+key1.key);    
         if(hm.containsKey(key1))       
            System.out.print(pt.data);
       }
   }
 }

因为我得到......

true0
9
true1
9
true2
9
true3    
9  
true4    
9

更新代码.....

   class K{ 
       long key;   
   }   

   class V{ 
      long[] v=new long[10];      
  }                                   

  public void  putHash(V val1){      
         //some code         
     V s=new V();               
     K gt=new K();            
     gt.key=val1.v[0];                
    if(hm.containsKey(keyArr[(int)gt.key])){         
                 s=hm.get(gt);    //get value of key if exists              
       //some code to modify s               
    }                 
   gt.key=val1.v[0];             
   hm.put(gt,s);  // put the modified value back to same key    
}      

谢谢大家为我提供答案......最后它运作良好...感谢大家的贡献....

4 个答案:

答案 0 :(得分:1)

HashMap存储密钥的引用。因此,如果您更改密钥,它将在HashMap中更改。如果您想要更改,请在for循环中移动语句K key1=new K();

答案 1 :(得分:0)

首先执行以下操作:

HashMap<K, V> hm = new HashMap<K, V>();
            K key1 = null;
            for (int i = 0; i < 5; i++) {
                key1 =new K();
                V val = new V();
                key1.key = i;
                val.data = i + 5;
                hm.put(key1, val);

            }

我认为问题在于你迭代HashMap中的项目

尝试执行以下操作以迭代Map:

Iterator it = hm.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry)it.next();
                System.out.println(((K)pairs.getKey()).key + " = " + ((V)pairs.getValue()).data);

                it.remove(); // avoids a ConcurrentModificationException
            }

您将获得正确的值。

或者您可以参考此答案here来了解如何遍历您的键或值。

并给我一些反馈

希望有助于此。

答案 2 :(得分:0)

您在每次循环迭代中使用相同的K key1对象,并且您正在修改同一个对象,即使它已经在地图中。您需要为地图中的每个条目创建不同的密钥K(或者直接使用Integer而不是创建自己的密钥类,这至少需要equals和{{1比你更多) - 或者,如果你按顺序编号,只需一个数组:hashCode

答案 3 :(得分:0)

对于您放入地图的每个条目,您必须实例化该密钥,否则您的最后一个条目将被覆盖。