在两个列表中查找共同元素

时间:2013-11-07 11:55:31

标签: java hibernate java-ee

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

这是我的CRVariable hibernate类:

@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)!

关于我失踪的任何想法?

1 个答案:

答案 0 :(得分:1)

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

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