为什么我的Hashmap仍然有重复项?

时间:2015-08-05 20:30:48

标签: java arrays hashmap duplicates

我有一个哈希映射,如果我找不到记录以避免重复,我将它添加到地图中。

    List<APPPRecord> PFRecord = null;
    while(scroll.next()){
        APPPRecord item = (APPPRecord) scroll.get(0);
        List<ARecord> recs = new ArrayList<ARecord>();
        unique(APPPRecord);
        recs.addAll(APPPRecord);

    HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>();
    for(ARecord records:recs){
        if(!uniqueRecs.containsKey(records.getId())){
            uniqueRecs.put(records.getId(), records);

        }

之后,我得到了我需要的值。

     List<ARecord> finalRecs = new ArrayList<ARecord>();
     finalRecs.addAll(uniqueRecs.values());

问题是我仍然有重复项,即使我的单元测试运行正常并且只添加了唯一的记录。这是我的单元测试:

    public void testGetUniqueResults(){
    APRecord p1 = new APRecord();
    p1.settId("l1");
    APRecord p2 = new APRecord();
    p2.setId("l2");
    APRecord p3 = new APRecord();
    p3.setId("l1");
    APRecord p4 = new APRecord();
    p4.setId("l4");
    List< APRecord > listPatch = new ArrayList< APRecord >();
    listPatch.add(p1);
    listPatch.add(p2);
    listPatch.add(p3);
    listPatch.add(p4);

    List<ARecord> recs = new ArrayList<ARecord>();
    recs.addAll(listPatch);

    HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>();
    for(ARecord records:recs){
        if(!uniqueRecs.containsKey(records.getId())){
            uniqueRecs.put(records.getId(), records);

        }


    }
    Iterator it = uniqueRecs.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey()); //outputs l4, l2, l1 as expected

    }

    List<ARecord> finalRecs = new ArrayList<ACCMRecord>(uniqueRecs.values());
    for(ARecord record:finalRecs){
        System.out.println("records final "+record);
    }

为什么在运行实际服务代码时仍然会看到重复项?对此有什么解决方法?

编辑:Hashcode和等于实现

     public class APPPRecord extends AbstratAPRecord implements ARecord{
        private BigInteger autoID;
        private String ACompId = null;
       //setter and getter
      @Override
    public boolean equals(Object obj) {
    if(obj instanceof APPPRecord)
    {
        APPPRecord temp = (APPPRecord) obj;
        if(this.getACompId().equals(temp.getACompId()))
            return true;
    }
    return false;
}
@Override
public int hashCode() {
    return (this.getACompId().hashCode());        
}}

更新:我明白了。问题出在另一个班级。

0 个答案:

没有答案
相关问题