2014-10-01 89 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