![](/img/trans.png)
[英]Comparing the sum of two ArrayLists of objects using 'compareTo'
[英]Comparing two ArrayLists of Objects
我的班級叫學生。 另外,我為學生A和學生B有兩個數組列表。
學生A可以是:瑪麗亞,亞歷克斯,洛拉,弗拉德,勞倫,凱瑟琳。
學生B是來自A的學生:Maria,Alex
學生A已存儲正確的ID和名稱。 但是學生B僅准備了姓名和存儲的硬編碼ID。
我將這兩個列表分開,現在要執行以下操作:
如果瑪麗亞表格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
}
}
}
您的迭代沒有按照您的意圖進行。 您要一遍又一遍地比較兩個數組中索引“ i”的元素,而不是索引“ i”中的A中的元素和索引“ j”中的B中的元素。
如果您打印出要比較的每個學生的姓名,您應該清楚知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.