我想问一下是否有办法区分两个DefaultListModel的包含元素。例如:有2个模型,第1个包含a,b,c,d,第2个模型包含a,b,所以我想比较两个模型并在数组中返回“d”和“c”。谢谢。
答案 0 :(得分: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)