mibutec
mibutec

Reputation: 2997

Replace values in a java collection

I want to change the values of a collection of unknown type. I found java.util.Collections.replaceAll, but that works only for Lists. I helped myself creating a new new Collection and adding the changed elements.

if (o instanceof Collection) {
            Collection<Object> newCollection = (Collection<Object>) o.getClass().newInstance();
            for (Iterator<Object> it = ((Collection<Object>)o).iterator(); it.hasNext(); ) {
                newCollection.add(doSomethingWith(it.next()));
            }

            return newCollection;
}

But I liked to return the same List as result. Any ideas?

Upvotes: 0

Views: 2014

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Unfortunately, you cannot do this without requiring the collection to be of a specific type: since collections are not required to be ordered, the only method that lets you add items to a Collection is add, which inserts at an unspecified place in the collection.

Collection iterators do not let you modify collection elements either: some iterators let you remove the current item, but there is no "replace" method on collection iterators.

ListIterator<T> interface provides a set(T) method, but it locks you into using a List<T>, for which you already have a solution.

Note that your method is not bulletproof either - it relies on the assumption that a collection passed into it has an accessible parameterless constructor.

Upvotes: 1

Related Questions