简体   繁体   English

Java比较两个列表模型

[英]Java Comparing two list models

I would like to ask is there any way to differentiate the containing elements of two DefaultListModel. 我想问一下有什么方法可以区分两个DefaultListModel的包含元素。 For example : there are 2 models, 1st contain a,b,c,d, and the 2nd model contain a,b, so i would like a way to compare both models and return "d" and "c" in an array.Thank you. 例如:有2个模型,第一个包含a,b,c,d,第二个包含a,b,所以我想一种比较两个模型并在数组中返回“ d”和“ c”的方法。谢谢。

You have to build the intersection of both lists and then "subtract" it from the union: 您必须构建两个列表的交集,然后从联合中“减去”它:

// 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM