在CollectionUtils.isEqualCollection中使用Equator比较两个集合

时间:2017-09-22 09:58:37

标签: java generics collections interface

我必须使用Apache CollectionUtils.isEqualCollection比较两个集合。 它们具有相同的接口Compress,并有一个比较方法:

public boolean isTheSame(Compress compr);

但我不知道如何在我的代码中添加一个Equator。

来自文档:

isEqualCollection(Collection<? extends E> a, Collection<? extends E> b, Equator<? 
super E> equator)
Returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities.

我的代码:

    return CollectionUtils.isEqualCollection(filtLst3, filtLst4, equator);

我应该把Equator的方法放在我的集合类中吗? 或者可能是我应该写这样的东西(不工作的代码):

...

    Eq equator = new Eq<Compress>();
    return CollectionUtils.isEqualCollection(filtLst3, filtLst4, equator);
}

public static class Eq<Compress> implements Equator {

    public boolean equate(Object o1, Object o2) {
        Compress c1 = (Compress) o1;
        Compress c2 = (Compress) o1;

        return c1.isTheSame(c2);
    }

    public int hash(Object o) {
        // TODO Auto-generated method stub
        return 0;
    }

}

我真的很感激任何帮助!

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

 public boolean isTheSame(Collection<? extends Compress> a, Collection<? extends Compress> b) {
        Equator<Compress> compressEquator = new CompressEquator();
        return CollectionUtils.isEqualCollection(a, b, compressEquator); 
 }

    public static class CompressEquator implements Equator<Compress> {

    public boolean equate(Compress c1, Compress c2) {
       return c1.isTheSame(c2);
    }
    //
  }
}