When a LinkedList is not good enough – OR – copying a Set to a List

I had a need to remove duplicates from a pre-existing list. I tried:

ids = new LinkedList<WatchedId>(new LinkedHashSet<WatchedId>(ids));

Seems easy enough, but the list kept returning no elements. I started clicking through the code and found the LinkedList constructor that takes a collection eventually calls

LinkedList.addAll(int size, Collection)

That method has the following line

Object[] a = c.toArray();

The implementation was in AbstractCollection.toArray(). I stepped through the code and I saw that the nodes were not being moved. Maybe that is a Mac JVM bug? I changed the type to an ArrayList and it worked. Maybe it has something to do with going from a double-linked backing object to a double-linked backing object.

ids = new ArrayList<WatchedId>(new LinkedHashSet<WatchedId>(ids));
This entry was posted in Collections, Java and tagged , , , , , , , , . Bookmark the permalink.

Leave a comment