【问题标题】:Comparing two ArrayLists of Objects比较两个对象的 ArrayList
【发布时间】:2017-04-30 18:24:29
【问题描述】:

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

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

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

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

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

如果 Maria 形式的数组 A 具有学生 ID: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
   }
  }
 }

【问题讨论】:

  • 这听起来有点像你主要抛弃了你的家庭作业和老师希望你填写的“模板”代码。你看,我们帮助解决具体问题,而不是“你能帮我做那件事吗”。
  • 您是否正在尝试将 A 到 B 的 id 填充到它们对应的名称中?
  • 是的。问题是:我已经有了 A 的所有正确 id。现在我需要将这些 id 与相应的名称一起设置为 B ArrayList。
  • 这不是作业。这是我的练习,与大学无关。

标签: java arraylist unique


【解决方案1】:

您的迭代没有按照您的意图进行。您一遍又一遍地比较两个数组中索引“i”处的元素,而不是 A 中索引“i”处的元素和 B 中索引“j”处的元素。

如果您打印出您比较的每个学生的姓名,您应该很清楚。

【讨论】:

  • 是的,对不起。我编辑了我的帖子。我实际上是在比较 i 和 j。所以它不想工作,也不知道为什么......
猜你喜欢
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 2021-06-04
  • 2013-01-15
相关资源
最近更新 更多