There are 2 problems with your implementation.
- You're not counting all of the items in the array. You should do either
i <= data.size() - 1
or i < data.size()
. Right now you're missing the last item.
- You're not adding items to the end of the list. Instead, you're repeatedly overwriting the zeroth (first) value. EDIT: Sorry, that was incorrect. You're inserting at the beginning of the list, which will work but is inefficient for the most commonly used lists (e.g. ArrayList).
Here is the fixed version. The problem areas are commented out with /* */
.
List<Object> newList = new ArrayList<Object>();
for (int i = 0; i < data.size() /* - 1 */ ; i++) {
if (!newList.contains(data.get(i)))
newList.add( /* 0, */ (data.get(i)));
}
return newList;
EDIT: Using contains(...)
on a list is slow. You can optimize and simplify this by using a Set
. A set is a collection which has unique values. Adding the same value twice has no effect. We can take it a step further and use a LinkedHashSet
as the implementation class, which will maintain the same ordering as was in the original list.
return new ArrayList<Object>(new LinkedHashSet<Object>(data));