使用两组(假设X
是您的对象的类):
// Returns a set of all duplicates in a list
public Set<X> getDuplicates(final List<X> list)
{
final Set<X> dups = new HashSet<X>();
final Set<X> set = new HashSet<X>();
/*
* Cycle through all elements in the original list. Add it to "set":
*
* - if the .add() method returns true, this is the first time the element is seen;
* - if it returns false, then this is not the first time, it is a duplicate:
* add it to "dups".
*/
for (final X element: list)
if (!set.add(element))
dups.add(element);
return dups;
}
如果操作未修改集合,则集合.add()
将返回 false ,这意味着元素是否已经存在。
将该函数复制/粘贴到您现有的代码中,并将上面的代码段替换为:
for (final X dup: getDuplicates(error_dub))
System.out.println(dup + " is duplicated");
重要说明:getDuplicates()
编写的函数不会尊重元素顺序。如果顺序对您很重要,请dups
用 aLinkedHashSet
而不是 a替换HashSet
。