0

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?

1
  • How about this: Collections.replaceAll(new ArrayList(yourCollection), old, new);. If you want to return it, just save the new list to a variable before doing the replacement. Commented Dec 1, 2014 at 21:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.