1

我有两个 CRVariable 类型的数组列表(休眠类),我想找到它们的共同元素(我猜是交叉点)。

这是我的 CRVariable 休眠类:

@Entity
@Table(name = "imageviewer_crvariable")
public class CRVariable implements Serializable   {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name = "VarId")
    private Long varId;

    @Column(name = "VarName", unique=true)
    private String varName;

    @Column(name = "VarDescription")
    private String varDescription;

    private String state;

    @ManyToMany(mappedBy="crvariables")
    private Set<CRImageType> crimagetypes = new HashSet<CRImageType>();

    @OneToMany(mappedBy="cRVariable")
    private Set<CRFormField> cRFormFields;
        ....

所以我试图通过以下方式使用 Collection#retainAll() 方法:

...
List<CRVariable> variablesForCurrentImageType = new ArrayList<CRVariable>();
variablesForCurrentImageType = getCRVariablesForImageType(mySelectedImages.get(k));
...
List<CRVariable> mySelectedVariables = Arrays.asList(selectedVariables);
...
Collection<CRVariable> colA1 = new ArrayList<CRVariable>();
colA1.addAll(mySelectedVariables);

Collection<CRVariable> colB1 = new ArrayList<CRVariable>();
colB1.addAll(variablesForCurrentImageType);
...
if(colA1.size()>colB1.size()){
    colA1.retainAll(colB1); //intersection
    System.out.println(">>>> INTERSECTION SIZE: " + colA1.size());
} else {
    colB1.retainAll(colA1); //intersection
    System.out.println(">>>> INTERSECTION SIZE: " + colB1.size()); 
}
...

但无论我尝试哪种组合,我总是得到 colA1 或 colB1 大小为零(0)!

关于我错过了什么的任何想法?

4

1 回答 1

1

您可能没有正确实现 equals() 。

retainAll() 方法不能自动知道哪些对象是相等的,所以你必须提供它。

于 2013-11-07T11:57:16.657 回答