2014-10-01 56 views
0

我想問,是否有任何方法來區分兩個DefaultListModel的包含元素。例如:有2個模型,第1個包含a,b,c,d,第2個模型包含a,b,所以我想要一種方法來比較兩個模型並在數組中返回「d」和「c」。謝謝。Java比較兩個列表模型

+0

使用一些技巧,可以考慮使用'Set',它不允許重複..你能達到什麼你要。 – Maroun 2014-10-01 15:55:44

回答

1

你必須建立兩個列表的交集,然後從聯盟「減」是:

// consider m1 and m2 your two DefaultListModels: 
DefaultListModel m1 = ... ; 
DefaultListModel m2 = ... ; 

// retrieve the elements 
List<?> elements1 = Arrays.asList(m1.toArray()); 
List<?> elements2 = Arrays.asList(m2.toArray()); 

// build the union set 
Set<Object> unionSet = new HashSet<Object>(); 
unionSet.addAll(elements1); 
unionSet.addAll(elements2); 

// build the intersection and subtract it from the union 
elements1.retainAll(elements2); 
unionSet.removeAll(elements1); 

// unionSet now holds the elements that are only present 
// in elements1 or elements2 (but not in both) 
+0

工作!非常感謝你兄弟..你救了我的一天 – User420 2014-10-01 18:06:54