比较两个对象的ArrayLists

时间:2017-04-30 18:24:30

标签: java arraylist unique

我有一个名为Student的班级。 我还有两个学生A和学生B的阵列表。

学生A可能是:Maria,Alex,Lora,Vlad,Lauren,Catherine。

学生B是来自A:Maria,Alex的一些学生

学生A存储了正确的ID和名称。 但学生B只准备了名字和硬编码的id。

我将这两个列表分开,现在要执行以下操作:

如果Maria表格阵列A的学生编号为:2427

来自阵列B的Maria应该收到相同的学生ID。

你能帮我做一下。

 //array lists of students a and b
public void common(){

     ArrayList<ArrayList<Student>> lists = new ArrayList<ArrayList<Student>>();
     lists.add(a);
     lists.add(b);

     System.out.println(getCommonElements(lists));
     for (int i = 0; i < lists.size(); i++) {
         aa = lists.get(0);
         bb = lists.get(1);

     }
     System.out.println(aa);
     System.out.println(bb);
}


public static <T> Set<T> getCommonElements(Collection<? extends Collection<T>> collections) {

    Set<T> common = new LinkedHashSet<T>();
    if (!collections.isEmpty()) {
       Iterator<? extends Collection<T>> iterator = collections.iterator();
       common.addAll(iterator.next());
       while (iterator.hasNext()) {
          common.retainAll(iterator.next());
       }
    }
    return common;
}

提前谢谢! 问题很少是为什么这不起作用?

for (int i = 0; i < a.size(); i++) {
  for (int j = 0; j < b.size(); j++) {

      if(a.get(i).getName().equals(b.get(j).getName())){
                //does not go there at all
   }
  }
 }

1 个答案:

答案 0 :(得分:0)

你的迭代没有按照你的意思去做。您正在比较索引的元素&#39; i&#39;在两个数组中反复使用,而不是索引中的A中的元素&#39; i&#39;和索引中的B中的元素&#39; j&#39;。

如果你打印出你比较的每个学生的名字,你应该清楚。