从自定义对象数组中删除重复记录

时间:2015-08-03 19:24:48

标签: java arraylist

所以我有一个界面。

    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>();
        unique(APPPRecord);
        recs.addAll(APPPRecord);

我的recs有重复的记录,我正在尝试删除,并为每个重复的recod都有一个唯一的记录。 到目前为止,我已经尝试过Set和hash set,但无济于事。 任何帮助表示赞赏。

编辑:我已经尝试过哈希码并且等于。

    @Override
    public boolean equals(Object obj) {
    if(obj instanceof APPPRecord)
    {
        APPPRecord temp = (APPPRecord) obj;
        if(this.getACompId() == temp.getACompId())
            return true;
    }
    return false;
}
@Override
public int hashCode() {
    return (this.getACompId().hashCode());        
}

在服务中:

    private List< APPPRecord > unique(List< APPPRecord > list) {
    List< APPPRecord > uniqueList = new ArrayList< APPPRecord >();
    Set< APPPRecord > uniqueSet = new HashSet< APPPRecord >();
    for (APPPRecord obj : list) {
        if (uniqueSet.add(obj)) {
            uniqueList.add(obj);
        }
    }
    return uniqueList;
}

1 个答案:

答案 0 :(得分:0)

啊,好的。您的错误可能是这样的:

 if(this.getACompId() == temp.getACompId())

ACompId是一个字符串。您无法将字符串与==进行比较。改为使用“等于”:

if(this.getACompId().equals(temp.getACompId()))

==仅比较身份,意味着只有==他自己的​​字符串 - 而不是==equal字符串。对于==工作,它们必须是同一个对象,但“A”和“A”不一定是。它们可以是恰好具有相同内容的两个不同的对象。

很容易陷入这个陷阱,因为当你直接写它时......

String x = "A";
String y = "A";
boolean same = x == y; // will probably be true, since the compiler can optimze it into the same object

但这很可能不适用于在运行时生成的动态字符串。所以,为了缩短它,不要依赖“==”来比较“等于”。如果你想比较“同一个对象”(你可以在一些非常特殊的情况下做,当然 - 字符串通常不是其中之一),只能使用“==”。