所以我有一个接口。
public interface ARecord {
public BigInteger getAutoID();
public String getACompId();
}
和
public class APPPRecord extends AbstratAPRecord implements ARecord{
private BigInteger autoID;
private String ACompId = null;
//setter and getter}
在服务,
List<APPPRecord> PFRecord = null;
while(scroll.next()){
APPPRecord item = (APPPRecord) scroll.get(0);
List<ARecord> recs = new ArrayList<ARecord>();
recs.addAll(PFRecord);
我的PFRecord列表有被复制的结果。我必须使用散列映射来检查ACompId是否包含键。如果键已经存在,不要将它传递给recs.addAll。我该怎么做呢?感谢任何帮助
更新:我尝试设置,仍然看到重复的结果与HashCode()和equals()在我的模型类。
for(ARecord records:recs){
uniqueRecs.put(records.getACompId(), records);
Set<String> keys = uniqueRecs.keySet();
for(String key: keys){
log.debug("keys " + key);
}
}
也尝试hashMaps.
HashMap<String, ARecord > uniqueRecs = new HashMap<String, ARecord >();
for(ARecord records:recs){
if(!uniqueRecs.containsKey(records.getACompId())){
uniqueRecs.put(records.getACompId(), records);
for (String key : uniqueRecs.keySet()) {
log.debug("unique record " + key);
}
}
}
它们仍然产生重复的结果。什么好主意吗?
替换List<ARecord> recs = new ArrayList<ARecord>();
与Set<ARecord> recs = new HashSet<ARecord>();
并确保ARecord
的实现正确地实现了hashcode
/equals
方法,以便您的集合只包含不同的实例。
使用HashMap<K,V>
类,本文档将为您提供所需的API。
根据您的要求,您可以使用.containsKey(Object key)
方法来检查密钥是否已经存在。
更新:我建议这样做,因为你要求HashMap
,如果重复是你唯一的问题,那么你可以在你已经拥有的列表上使用.contains(Object o)
方法。接口List<>
提供了这个方法,该方法根据值的存在返回boolean
值。